LeetCode(11)题解: Container With Most Water

时间:2023-01-09 21:55:35

https://leetcode.com/problems/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.

 

思路:

考虑从边界向里缩减范围。最重要的是注意到,假设现在边界的height是a和b,那么想在内部有别的点能比a、b框成的体积大,那么这个点一定得比a、b中的最小者大。所以不断从边界height较小的点向内缩减,直到内部为空。

只需遍历数组一次,所以复杂度为O(n)。

 

AC代码:

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         int i,j,n=height.size(),a=0,b=n-1,contain=min(height[0],height[n-1])*(n-1);
 5         while(a<b){
 6             if(height[a]<height[b]){
 7                 for(i=a;i<b;i++){
 8                     if(height[i]>height[a])
 9                         break;
10                 }
11                 if(min(height[i],height[b])*(b-i)>contain){
12                     contain=min(height[i],height[b])*(b-i);
13                 }
14                 a=i;
15             }
16             else{
17                 for(j=b;j>a;j--){
18                     if(height[j]>height[b])
19                         break;
20                 }
21                 if(min(height[j],height[a])*(j-a)>contain){
22                     contain=min(height[j],height[a])*(j-a);
23                     }
24                 b=j;
25             }
26         }
27         return contain;
28     }
29 };