Leetcode题解-11. Container With Most Water
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
思路
一种简单的想法就是用两重遍历,那时间复杂度就是O(n^2)了,比较简单这里就不再赘述了。
这里用另外一种方法:用max表示最大容量,开始时用i指向数组头,j指向数组尾,求出i、j之间的容量min{height[i], height[j]}·(j-i),与max比较,max比当前所求容量小则将当前容量赋值给max。然后倘若height[i]小于height[j],则i++,反之j- -。重复上述过程直至i等于j,返回max。这里时间复杂度为O(n).
证明:假设height[i] < height[j],container1 =height[i]·(j-i),则container1 > container2(container2 = height[k]·(k-i)(i < k < j)),所以不必要考虑container2,所以将i++。反之height[i] > height[j]同样的道理,只需要将j- -。
代码
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1;
int max = 0;
while(i != j){
int min = 0;
int cur = 0;
if(height[i] <= height[j]){
min = height[i];
cur = min * (j-i);
i++;
}
else{
min = height[j];
cur = min * (j-i);
j--;
}
if(max < cur) max = cur;
}
return max;
}