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向右移动尝试其他组合。
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; }
相关文章推荐
- 11. Container With Most Water
- [leetcode刷题系列]Container With Most Water
- leetcode[11]Container With Most Water
- Leetcode -- Python --Container With Most Water
- leetcode---Container With Most Water
- Middle-题目31:11. Container With Most Water
- [Leetcode] container with most water 最大水容器
- Container With Most Water
- Leetcode Container With Most Water
- LeetCode OJ Container With Most Water
- leetcode Container With Most Water python
- 11.Container With Most Water
- LeetCodeOJ_11_m_Container With Most Water
- Leetcode | Container With Most Water
- [Leetcode] Container With Most Water 能装最大水的容量
- Container With Most Water
- LeetCode: Container With Most Water
- Container With Most Water
- container-with-most-water
- Container With Most Water