aiheshan

有多自律,才能有多自由

导航

leetcode 11. Container With Most Water

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

题目:给定n个非负的数a1...an,其中(i,ai)表示x轴为i,y轴为ai;取任意2个点与x轴的垂直线可以组合成一个容器,假设用这些容器来装水,则其中装水最多的容器可装水多少?

思路:这道题要注意理解题意,两个线的中间不管有没有更小的线,都是取两个线中小的那根为高。

所以假设选取i,j(j>i)的两根垂线,则装水面积为area=min(heigth[i],height[j])(j-i);

假设height[i]<height[j],想要装更多的水,只能是i++;因为i为短的那根,只有i移动才可能增加高度。

所以每次短的那根移动,才有可能装水面积更多。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int i=0;
        int j=height.size()-1;
        int maxarea = 0;
        while(i<j){
          int temp = min(height[j],height[i])*(j-i);
          if(maxarea < temp)
             maxarea = temp;
          if(height[i]<height[j])
          {
              i++;
          }
          else 
            j--;
        }
        return maxarea;
    }
};

 

posted on 2016-08-27 09:49  aiheshan  阅读(164)  评论(0编辑  收藏  举报