LeetCode之11---Container With Most Water

题目:

  

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.

题目大意:

  给定一个数组,在数组中选取两个数字,数字的下标代表水桶的底面积,数字中较小的一个作为最终的桶高(短板定律),求这组数中最大的装水容量。
  按照题目的英文翻译过来看起来很奇怪。。。所以,转换成表达式吧,设i,j两个下标,求min(a[i], a[j]) * abs(i - j)的最大值。

思路1:

  最先想到的是暴力求解法,一个双重循环,枚举所有情况,求得最大值然后返回。
  时间复杂度为O(n^2),不出意外的超时了。。。。

代码1:

class Solution {
public:
    int maxArea(std::vector<int>& height) {
        int pos, max = 0;
        for (int i = 0; i < height.size(); ++i) {
            for (int j = i + 1; j < height.size(); ++j) {
                int tmp = (height[i] < height[j] ? height[i] : height[j]) * (j - i);
                if (max < tmp) {
                    pos = i;
                    max = tmp;
                }
            }
        }
        
        return max;
    }
};

思路2:

  第二个思路采用贪心的解决思路,先将距离置为最大(即:a.size() - 1 - 0),然后每次在缩小距离的同时让最小数不断增大,从而求得最优解。具体操作步骤如下:
  将i置为0,将j置为a.size()-1,然后每次判断a[i]<a[j]是否成立,如果成立则++i,如果不成立则--j(++i和--j的原因是不断增大所选择的较小值,如果选择此时的较小值进入下一次循环的话只会使下一次迭代的最小值比本次最小值小或等于本次最小值,这样则不符合最优解的条件)。

代码2:

class Solution {
public:
    int maxArea(std::vector<int> &height) {
        int max = 0, i = 0, j = height.size() - 1, tmp = 0;
        
        while (i < j) {
            bool flag = height[i] < height[j] ? true : false;
            if (flag) {
                ++i;
                tmp = height[i] * (j - i);
            } else {
                --j;
                tmp  = height[j] * (j - i);
            }
            if (tmp > max) {
                max = tmp;
            }
        }
        
        return max;
    }
};


posted @ 2016-04-08 18:00  Jung_zhang  阅读(137)  评论(0编辑  收藏  举报