LeetCode刷题Medium篇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 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

十分钟尝试

关键是抽象出数学模型,我没有抽象出来,看了提示后,写了一下,代码如下,二层循环

class Solution {
    public int maxArea(int[] height) {
        int maxArea=0;
        for(int i=0;i<height.length;i++){
            for(int j=i+1;j<height.length;j++){
                maxArea=Math.max(maxArea,Math.min(height[i],height[j])*(j-i));
            }
        }
        return maxArea;
    }
}

答案说有线性时间的解法,我尝试一下。两层for循环的线性修改就是用两个指针,代码如下:

class Solution {
    public int maxArea(int[] height) {
       int p=0;
       int q=height.length-1;
        int maxArea=0;
       while(p<q){
           maxArea=Math.max(maxArea,Math.min(height[p],height[q])*(q-p));
           p++;
           q--;
       }
        
       return maxArea;
    
    }
}

结果不对,问题出在哪里?不要两个指针都移动,这样不能全部覆盖。那个低移动哪个。

class Solution {
    public int maxArea(int[] height) {
       int p=0;
       int q=height.length-1;
        int maxArea=0;
       while(p<q){
           maxArea=Math.max(maxArea,Math.min(height[p],height[q])*(q-p));
           if(height[p]<height[q]){
               p++; 
           }
          else{
              q--; 
          }
          
       }
        
       return maxArea;
    
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85283763