leetcode_11_盛最多水的容器

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器。

 

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

 

 

class Solution {
    public int maxArea(int[] height) {

        //双指针操作数组
        //容器可以容纳的水  =  两个指针指向的数字中较小值∗指针之间的距离
       int pre = 0;
       int last = height.length-1;
       int max =0;
       while(pre != last){
            int min = Math.min(height[pre],height[last]);
            int res = min*(last-pre);
            if(res>max){
                max =res;
            } 
            if(height[pre]<height[last]){
                pre ++;
            }else{
                last --;
            }
       }   
    return max;

    }
}

//官方题解
// public class Solution {
//     public int maxArea(int[] height) {
//         int l = 0, r = height.length - 1;
//         int ans = 0;
//         while (l < r) {
//             int area = Math.min(height[l], height[r]) * (r - l);
//             ans = Math.max(ans, area);
//             if (height[l] <= height[r]) {
//                 ++l;
//             }
//             else {
//                 --r;
//             }
//         }
//         return ans;
//     }
// }

 

posted @ 2021-06-08 15:41  格格巫掌门  阅读(28)  评论(0)    收藏  举报