11.盛最多水的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。(哈哈哈, 你高估我了)
解题思路:
通过双指针的思想,从两头往中间遍历的同时计算需要的结果,注意每次移动较小的一个。
Swfit
func maxArea(_ height: [Int]) -> Int {var maxArea:Int = 0var i:Int = 0var j:Int = height.count-1while(i < j) {if height[i] > height[j] {maxArea = max(maxArea, height[j]*(j-i))j-=1}else {maxArea = max(maxArea, height[i]*(j-i))i+=1}}return maxArea}
OC
- (NSInteger)maxArea:(NSArray *)height {NSInteger maxArea = 0;NSInteger i=0;NSInteger j = height.count-1;while (i<j) {if ([height[i] integerValue] < [height[j] integerValue]) {maxArea = MAX(maxArea, [height[i] integerValue] * (j-i));i++;}else {maxArea = MAX(maxArea, [height[j] integerValue] * (j-i));j--;}}return maxArea;
}