【leetcode】Container With Most Water(middle)

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.

 

思路:

肯定是要确定水槽的左右边界位置,需要两个变量l1,l2 分别从最左边和最右边收缩。收缩规则是,比较矮的那一边向中间靠拢。更新水量。

我自己的代码:

int maxArea(vector<int> &height) {

        int ans = (height.size() - 1) * min(height[0], height.back()) ;

        int l1, l2, h1, h2;

        h1 = 0; h2 = height.size() - 1;

        l1 = h1; l2 = h2;

        while(l1 < l2)

        {

            if(height[l1] > height[h1])

            {

                h1 = l1;

                int tmp = (l2 - l1) * min(height[l2], height[l1]);

                ans = (tmp > ans) ? tmp : ans;

            }

            if(height[l2] > height[h2])

            {

                h2 = l2;

                int tmp = (l2 - l1) * min(height[l2], height[l1]);

                ans = (tmp > ans) ? tmp : ans;

            }

            if(height[l1] < height[l2])

            {

                l1++;

            }

            else if(height[l1] > height[l2])

            {

                l2--;

            }

            else

            {

                l1++; l2--;

            }

        }

        return ans;

    }

 

大神的代码就简洁很多:

int maxArea(vector<int> &height) {

    int left = 0, right = height.size() - 1;

    int maxWater = 0;

    while(left < right){

        maxWater = max(maxWater, (right - left) * min(height[left], height[right]));

        height[left] < height[right] ? left++ : right--;

    }

    return maxWater;

}

 

你可能感兴趣的:(LeetCode)