leetcode 11. Container With Most Water

来源:互联网 发布:广东工业大学矩阵分析 编辑:程序博客网 时间:2024/06/05 16:18

相关问题

Discription

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.

思路

双指针:用两个指针分别表示容器的左边界 left 和右边界 right。
初始 left 指向最左,right 指向最右。
考虑如下两点事实:

  1. 容器的盛水量取决于短的边界高度 min(height[left], height[right]) 以及水平长度 right - left ;
  2. 随着 left 向右移动或者 right 向左移动,水平长度必然减小;

故只有提高短边界的高度 min(height[left], height[right]) 才有肯能提高盛水量。

时间复杂度:O(n)
空间复杂度:O(1)

代码

class Solution {public:    int maxArea(vector<int>& height) {        int left = 0, right = height.size() - 1;        int max_area = min(height[left], height[right]) * (right - left);        while (left < right)        {            int min_h = min(height[left], height[right]);            if (height[left] == min_h)                                  // 找到瓶颈                while (left < right && height[left] <= min_h) left++;            else                while (left < right && height[right] <= min_h) right--;            if (left < right)            {                int area = min(height[left], height[right]) * (right - left);                max_area = max(area, max_area);            }            else                break;        }        return max_area;    }};
原创粉丝点击