11. Container With Most Water

题目链接
tag:

  • Medium;
  • Two Pointers;

question
  Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

思路:
  比较简单,我们需要定义leftright两个指针分别指向数组的左右两端,然后两个指针向中间搜索,每移动一次算一个值和结果比较取较大的,容器装水量的算法是找出左右两个边缘中较小的那个乘以两边缘的距离,对于相同的高度们直接移动leftright就行了,不再进行计算容量了,代码如下:

C++ 解法:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0, left = 0, right = height.size()-1;
        while (left < right) {
            int h = min(height[left], height[right]);
            res = max(res, h*(right-left));
            while (left < right && h == height[left]) ++left;
            while (left < right && h == height[right]) --right;
        }
        return res;
    }
};

Python 解法:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        res, left, right = 0, 0, len(height) - 1
        while left < right:
            high = min(height[left], height[right])
            res = max(res, high*(right-left))
            while left < right and high == height[left]:
                left += 1
            while left < right and high == height[right]:
                right -= 1
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容