码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 11 -- Container With Most Water

时间:2015-05-30 09:28:02      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:array   leetcode   

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.


题意:
给于一个序列,序列里面的数字代表高度,数字下标之差作为底边,两个高度之间能当作容器装水且装水量取决与两者较低值和两者在序列中的下标之差。


思路:
1.最普通的暴力求解法,但是测试时显示超时了,O(n^2)
2.类似贪心的算法,取左边界和右边界,计算,然后每次选取较低的高度的下标推进,从而保留高的下标记,保证下一次我们可能选取到较优的解。比如,cont = min(a[i],a[j])*(j-i) and i < j, 如果a[i] < a[j],那么=>i++,因为i++j--容器底边都是减1,而我们保留高度高的a[j],下一次计算时肯定会比执行j--的容量大。也就是每次尽量向更优的解去移动,至于有些没移动到的范围是因为我们在判断时(如上面的例子)就把它pass掉了,时间复杂度O(n)


代码:

class Solution {
public:
    typedef vector<int>::iterator vter;
    int maxArea(vector<int>& height) {
        auto left = height.begin();
        auto right = height.end()-1;
        int max = 0;
        while(left != right){
            vter tmp = min(left, right);
            int val = (right-left)*(*min(left, right));
            if(max < val){
                max = val;
            }
            if(tmp == left){
                ++left;
            }else{
                --right;
            }
        }
        return max;
    }
    vter min(vter a, vter b){
        return *a < *b ? a : b;
    }
};

leetcode 11 -- Container With Most Water

标签:array   leetcode   

原文地址:http://blog.csdn.net/wwh578867817/article/details/46240731

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!