LeetCode:11. ContainerWithWater(Medium)

时间:2021-12-06 14:29:48

原题链接:https://leetcode.com/problems/container-with-most-water/description/

题目要求:给定n个非负整数a1,a2,...,an ,每一个整数对应一个坐标(i,a)。以(i,0)和(i,a)为端点画一条线段,现在选择两条线段,以x轴为底构成一个容器,请问选择那两条线段时可以使容器盛更多的水?

注意:“短板效应”,容量取决于短的那条边,以及两条线段之间的距离

思路:求出Max[min(line1,line2)*(i1-i2)]

方法一:暴力解决,去任意两条不同线段构成容器,求出最大值。时间复杂度O(n2),空间复杂度O(1)。

方法二:两端逼近,从数组的两端开始,不断向中间逼近。时间复杂度O(n),空间复杂度O(1)

 package com.huiAlex;

 import java.util.Random;

 public class ContainerWithMostWater11 {

     public static void main(String[] args) {
int[] height = new int[10];
Random ran = new Random();
for (int i = 0; i < height.length; i++) {
height[i] = ran.nextInt(10);
System.out.println(height[i]);
}
ContainerWithMostWater11 cw = new ContainerWithMostWater11();
int a = cw.maxArea(height);
int b = cw.maxArea2(height);
System.out.println("area: " + a);
System.out.println("area2:" + b);
}
// 两端逼近
public int maxArea(int[] height) {
int maxarea = 0;
int l = 0;
int r = height.length - 1;
while (1 < r) {
maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r])
l++;
else
r--;
}
return maxarea;
}
// 暴力解决
public int maxArea2(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;
} }