【LeetCode】Container With Most Water

来源:互联网 发布:台湾用大陆网络语言 编辑:程序博客网 时间:2024/06/03 17:02

Description

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 and n is at least 2.

Code

class Solution {public:    int maxArea(vector<int>& height) {        int left = 0, right = height.size() - 1;        int maxV = 0, vol;        while (left != right) {            vol = (right - left) * min(height[right], height[left]);            maxV = max(maxV, vol);            if (height[left] < height[right])                // 左边那条线是短板,如果固定左边的板,让right--,那么新形成的容器一定会容积更小!                ++left;            else                --right;        }        return maxV;    }};                

Review

这道题中也用了将两个变量分别初始化为区间头尾,根据一定条件将头向后移动,或将尾向前移动的方法。
题中要求的是最大容量,3Sum Closest要求的是最接近的值,或这种情况下可以用这个思路?

这道题中的限制条件是短板长度,既然有一边是短板了,不妨设左边是短板,那么右边再往左边靠近,得到的结果肯定比原来的结果还要小,干脆可以不考虑左边是短板的其他情况了,直接让左边的下一块板子当左板好了。
3Sum Closest中的限制条件是两个数的和。可以根据和target的大小关系来决定如何移动数字才能更靠近target一些。

0 0
原创粉丝点击