LeetCode之双指针(3)

来源:互联网 发布:淘宝2017年双十一 编辑:程序博客网 时间:2024/05/23 15:07

11. Container With Most Water

题目链接:

https://leetcode.com/problems/container-with-most-water/

题目描述:

给一个高度数组,代表x轴上有一些给定高度的竖线,求两条竖线与x轴构成的容器能容纳最大多少的水面积。

题目分析:

curCapacity=min(height[low],height[high])*(high-low)

感谢

http://www.th7.cn/Program/c/201505/447082.shtml

一开始没懂题几个意思啊,求能装多少水,这咋算底面积啊。

双指针,一个从头开始走,一个从尾开始走,高度小的前进,为看之后有没有高度大的来更新curCapacity。

代码:
class Solution {public:    int maxArea(vector<int>& height) {        int low=0;        int high=height.size()-1;        int capacity=0;        int cur=0;        while(low<high){            cur=min(height[low],height[high])*(high-low);            if(capacity<cur){                capacity=cur;            }            if(height[low]>height[high]){                high--;            }            else{                low++;            }        }        return capacity;    }};
0 0
原创粉丝点击