从零单刷Leetcode(JAVA描述)——11. 盛最多水的容器

链接:https://leetcode-cn.com/problems/container-with-most-water
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

在这里插入图片描述

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

初见这道题,看到面积与x轴关系,第一时间想到用map做,但并不能利用值关系减少循环次数,结果碰到大数据量的测试用例时过不去。

//原始代码,复杂度O(n^2),非AC、报TLE
class Solution {
    public int maxArea(int[] height) {
        Map<Integer,Integer> map=new HashMap<>();
        int max=0,s=0;
        for(int i=0;i<height.length;i++){
            map.put(i,height[i]);
        }
        for(int i=0;i<height.length;i++){
            for(int j=i+1;j<height.length;j++){
                if(map.get(j)>=map.get(i))
                    s=map.get(i)*(j-i);
                else 
                    s=map.get(j)*(j-i);
                 max=Math.max(max,s);
            }
        }
        return max;
    }
}

后来使用双指针AC

class Solution {
    public int maxArea(int[] height) {
        int left=0,right=height.length-1;
        int maxArea=0;
        while(left<right){
            maxArea=Math.max(maxArea,Math.min(height[left],height[right])*(right-left));
            //左边是短板,尝试右移比较
            if(height[left]<height[right])left++;
            else 
                right--;
        }
         return maxArea;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/waS_TransvolnoS/article/details/91491258
今日推荐