LEETCODE: Container With Most Water

来源:互联网 发布:mac vi 命令大全 编辑:程序博客网 时间:2024/04/30 09:58
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.

如何找到这个最大值,我原来想了一个n平方的算法,不过没有通过LEETCODE的测试。所以,必须找到一个时间效率更高的算法。

假设我们用两个指针,一个指向左边left,一个指向右边right。这个时候我们会有一个初始的容量。如果left的高度小于right的高度,那么我们知道right往左移动是不会得到我们想要的,只有left往右移动。(如果我们把right往左移动,容量是right新的位置和left中的小值乘上距离。)反之,right往左移动。


class Solution {public:    int maxArea(vector<int> &height) {        int left = 0;        int right = height.size() - 1;        int max = 0;        while(left < right) {            int length = right - left;            int temp = length * (height[left] < height[right] ? height[left] : height[right]);            max = max > temp ? max : temp;            if(height[left] < height[right])                left ++;            else                right --;        }                return max;    }};



0 0
原创粉丝点击