LeetCode Container With Most Water

class Solution{
    public:
        int maxArea(vector<int>& height) {  
        int len = height.size(), low = 0, high = len -1 ;  
        int maxArea = 0;  
        while (low < high) {  
            maxArea = max(maxArea, (high - low) * min(height[low], height[high]));  
            if (height[low] < height[high]) {  
                low++;  
            } else {  
                high--;  
            }  
        }  
        return maxArea;  
    }
};

应该算是贪婪算法吧,直接从disscus里抄了,自己只能想出一个nlogn的,对贪婪没什么感觉,想不到

第二轮:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

以前leetcode还没有标flag,现在可以看到这题标了two pointer就是2sum这种类似,首先最大的可能是由两端的作为容器壁,然后慢慢往内收缩尝试,收缩过程中放弃比较低的容器壁。反正这次又没想出来还看错题目,智商拙计啊:

 1 // 9:44
 2 class Solution {
 3 public:
 4     int maxArea(vector<int>& height) {
 5         int len = height.size();
 6         int lo = 0, hi = len - 1;
 7         int maxarea = 0;
 8         while (lo < hi) {
 9             maxarea = max(maxarea, min(height[lo], height[hi]) * (hi - lo));
10             if (height[lo] < height[hi]) {
11                 lo++;
12             } else {
13                 hi--;
14             }
15         }
16         
17         return maxarea;
18     }
19 };

 

posted @ 2014-05-08 09:56  卖程序的小歪  阅读(154)  评论(0编辑  收藏  举报