您的位置:首页 > 大数据 > 人工智能

Container With Most Water

2013-10-10 18:47 281 查看
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.

思路:

贪心的方法,用left和right分别记录数组的两边,然后哪边小从哪边往里面移动。因为如果另一边的话只可能更小。

简单的证明:

假设一个中间状态时[(i, a), (j, b)],则 j 右边小于a的边和 i 左边 小于b的边都已经遍历过了。若a < b, j 向左移只会更小, j向右移如果是小于a的值则已经遍历,假设有大于a的值(k, c),则a左边一定又有大于c的值(m,d)使得到达j当前的位置(否则按照代码思路,右边指针会停留k在这等待左边指针向右移动到i),也就意味着[(m,d),(k,c)]访问过或者比它更大的结果访问过,而它一定会大于[(i,a),(k,c)],所以也没有必要再尝试这个状态。综上,j不需要动,i向右移动尝试其他组合。

int min(int a, int b){
if(a<b)
return a;
return b;
}
int maxArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = height.size();
int left = 0, right = n-1;
int max = min(height[left], height[right])*(right-left), tmp;
while(left < right){
if(height[left] < height[right])
left++;
else
right--;
tmp = min(height[left], height[right])*(right-left);
if(tmp > max)
max = tmp;
}
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: