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

LeetCode Container With Most Water

时间:2015-01-17 23:33:30      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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.


题意:x轴上的n条垂直线,求类似木板盛水的最大值

思路:双指针加贪心,每次对当前的l和r围成的水池计算面积,然后对于更新l或r的话,就看curL和curR的大小,贪心的来看的话,如果curL<curR的话,那么将l指针向右移动显然是比较好的,移动到的位置取决于是否能找到更大的curL,至于另外一种情况类似

class Solution {
public:
    int maxArea(vector<int> &height) {
        int l, r;
        int len = height.size() - 1;
        l = 0, r = len;
        int curL = height[l];
        int curR = height[r];
        int Max = 0;

        while (l < r) {
            int tmp = min(curL, curR) * (r - l); 
            if (Max < tmp) Max = tmp;
            if (curL > curR) {
                while(l < r && curR >= height[r]) r--;
                if (l < r) curR = height[r];
            } else {
                while (l < r && curL >= height[l]) l++;
                if (l < r) curL = height[l];
            }
        }

        return Max;
    }
};
















LeetCode Container With Most Water

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/42815387

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