原题链接:https://leetcode.com/problems/container-with-most-water/description/
题目要求:给定n个非负整数a1,a2,...,an ,每一个整数对应一个坐标(i,ai )。以(i,0)和(i,ai )为端点画一条线段,现在选择两条线段,以x轴为底构成一个容器,请问选择那两条线段时可以使容器盛更多的水?
注意:“短板效应”,容量取决于短的那条边,以及两条线段之间的距离
思路:求出Max[min(line1,line2)*(i1-i2)]
方法一:暴力解决,去任意两条不同线段构成容器,求出最大值。时间复杂度O(n2),空间复杂度O(1)。
方法二:两端逼近,从数组的两端开始,不断向中间逼近。时间复杂度O(n),空间复杂度O(1)
1 package com.huiAlex; 2 3 import java.util.Random; 4 5 public class ContainerWithMostWater11 { 6 7 public static void main(String[] args) { 8 int[] height = new int[10]; 9 Random ran = new Random(); 10 for (int i = 0; i < height.length; i++) { 11 height[i] = ran.nextInt(10); 12 System.out.println(height[i]); 13 } 14 ContainerWithMostWater11 cw = new ContainerWithMostWater11(); 15 int a = cw.maxArea(height); 16 int b = cw.maxArea2(height); 17 System.out.println("area: " + a); 18 System.out.println("area2:" + b); 19 } 20 // 两端逼近 21 public int maxArea(int[] height) { 22 int maxarea = 0; 23 int l = 0; 24 int r = height.length - 1; 25 while (1 < r) { 26 maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l)); 27 if (height[l] < height[r]) 28 l++; 29 else 30 r--; 31 } 32 return maxarea; 33 } 34 // 暴力解决 35 public int maxArea2(int[] height) { 36 int maxarea = 0; 37 for (int i = 0; i < height.length; i++) 38 for (int j = i + 1; j < height.length; j++) 39 maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i)); 40 return maxarea; 41 } 42 43 }