Leetcode刷题Java11. 盛最多水的容器

给你 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

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

//方法一:暴力法
//1.left bar x, right bar y, (x-y)*height_diff O(n^2)
//2.求最大值 
public int maxArea(int[] height) {
    if (height == null || height.length <= 0) {
                return 0;
    }
    int maxArea = 0;
    for (int i = 0; i < height.length - 1; i++) {
         for (int j = i + 1; j < height.length; j++) {
              int area = (j - i) * Math.min(height[i], height[j]);
              maxArea = Math.max(maxArea, area);
          }
    }
    return maxArea;  
}

//方法二:
//1.首先考虑最外围两条线段围城的区域,为了使面积最大化,需要考虑更长的两条线段之间的区域
//2.加入移动较长线段的指针向内侧移动,面积将受限于较短的线段而不会获得任何增加
//3.移动较短线段的指针,虽然宽度在减少,但是指针会得到一条较长的线段,从而有助于面积的增大
public int maxArea(int[] height) {
    int maxArea = 0;
    int left = 0, right = height.length - 1;
    while (left < right) {
        maxArea = Math.max(maxArea, (right - left) * Math.min(height[left],  height[right]));
        if (height[left] < height[right]) {
            left++;
         } else {
            right--;
          }
     }
     return maxArea;    
}

//方法三:
//1.定义两个指针,从数组两边开始遍历组成的矩形,并记录面积
//2.左右线段,哪边较低,哪边往中间移动
//3.当两个指针汇合时则遍历完成,返回最大面积
public int maxArea(int[] height) {
    int maxArea = 0;
    int left = 0, right = height.length - 1;
    while (left < right) {
          int width = right - left;
          int minHeight = height[right] < height[left] ? height[right--] : height[left++];
           maxArea = Math.max(maxArea,width * minHeight);
     }
     return maxArea;
}

//基于方法二进行优化
public int maxArea(int[] height) {
    int maxArea = 0, minHeight = 0;
    int left = 0, right = height.length - 1;
    while (left < right) {
          if (height[left] <= height[right]) {
              minHeight = height[left];
              maxArea = Math.max(maxArea, (right - left) * minHeight);
              while (left < right && height[left] <= minHeight) left++;
           } else {
                minHeight = height[right];
                maxArea = Math.max(maxArea, (right - left) * minHeight);
                while (left < right && height[right] <= minHeight) right--;
            }
      }
      return maxArea;
}
发布了19 篇原创文章 · 获赞 2 · 访问量 1448

猜你喜欢

转载自blog.csdn.net/Bonbon_wen/article/details/105421372