Leetcode:Container with most water菜鸟解法
2015-02-17 20:34
330 查看
这题想很久啊...一直觉得只能把n*(n-1)/2 种情况全考虑到才能解决
实际上用夹逼方法很容易就可解出来,从最左与最右看,如果左大于右,那怎么动左边都不可能让水增多,所以要移动右边,反之亦然,直到左右相碰
代码如下
class Solution {
public:
int maxArea(vector<int> &height) {
int left =0,result,chang,kuan;
int right = height.size()-1;
chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(kuan == 0) return 0;
result = chang*kuan;
while(left!=right){
if(height[left]<=height[right]){
left++;
}
else right--;
chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(result<chang*kuan) result = chang*kuan;
}
return result;
}
};
实际上用夹逼方法很容易就可解出来,从最左与最右看,如果左大于右,那怎么动左边都不可能让水增多,所以要移动右边,反之亦然,直到左右相碰
代码如下
class Solution {
public:
int maxArea(vector<int> &height) {
int left =0,result,chang,kuan;
int right = height.size()-1;
chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(kuan == 0) return 0;
result = chang*kuan;
while(left!=right){
if(height[left]<=height[right]){
left++;
}
else right--;
chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(result<chang*kuan) result = chang*kuan;
}
return result;
}
};
相关文章推荐
- leetcode之11. Container With Most Water(C++解法)
- leetcode Container With Most Water
- 【Leetcode】Container With Most Water
- leetcode--011 Container With Most Water
- 【leetcode】Container With Most Water
- LeetCode--Container With Most Water
- LeetCode 11 -- Container With Most Water
- [Leetcode] Container With Most Water
- LeetCode之Container With Most Water
- Container With Most Water - LeetCode 11
- Leetcode: Container With Most Water
- Container With Most Water--LeetCode
- leetcode_11_Container With Most Water
- 【leetcode】Container With Most Water
- LeetCode - 11 - Container With Most Water
- Leetcode:Container With Most Water
- Container With Most Water leetcode java
- Leetcode -- Python --Container With Most Water
- [LeetCode22]Container With Most Water
- LeetCode: Container With Most Water