11. Container With Most Water

文章目录如下

(1)自己的思路

(2)自己的代码

(3)别人的思路

(4)别人的代码

(5)对比自己的不足之处

题目

 

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.

 

(1)自己的思路

a.由于木桶效应,桶的容量取决于最短的那块木板,在求桶的容积的时候(就是求面积),高要取短的那个边

b.遍历所有的"桶",分别求出容积进行比较,返回最大的那个容积。

(2)自己的代码

class Solution {
public:
    int maxArea(vector<int>& height) {

        int maxArea = 0;
        int tmpArea = 0;
        int tmpHeight = 0;
        int tmpWidth = 0;

        for (int i = 0; i < height.size(); i++)
            for (int j = i; j < height.size(); j++)
            {
                tmpHeight = height[i] > height[j] ? height[j] : height[i];
                tmpWidth = abs(j-i);

                tmpArea = tmpHeight*tmpWidth;

                if (tmpArea > maxArea)
                    maxArea = tmpArea;
            }

        return maxArea;
    }
};

 

(3)别人的思路

从两边开始,往里缩小范围,其他思路跟我一样

 

(4)别人的代码

class Solution {
public:
    int maxArea(vector<int> &height) {
        int start = 0;
        int end = height.size() - 1;
        int result = INT_MIN;
        while (start < end) {
            int area = min(height[end], height[start]) * (end - start);
            result = max(result, area);
            if (height[start] <= height[end]) {
                start++;
            } else {
                end--;
            }
        }
        return result;
    }
};

(5)对比自己的不足之处

我觉得我与别人最大的差别在于,我把所谓的桶一个一个的对待了,而不是将桶范围性的对待。虽然乍一看范围性的比较好像不能遍历所有的桶,所以求出的最大值是不准确的,但是仔细想来,却不是那么回事。因为桶的容积(面积)由宽与高决定着,要求最大的容积(面积)无非就是要求宽最大,高最大。按照这种从两边到中间的排除法,是不会漏掉面积最大的那个桶的。虽然我这种方法也能求出来,但是时间复杂度为n²,而别人的时间复杂度为n,不是一个数量级的,所以还是别人的思路更好!

 

posted @ 2016-04-02 00:25  MAGICY  阅读(145)  评论(0编辑  收藏  举报