-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainerWithMostWater.java
More file actions
71 lines (59 loc) · 2.18 KB
/
Copy pathContainerWithMostWater.java
File metadata and controls
71 lines (59 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package ArrayTest;
/**
* 给定 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class ContainerWithMostWater {
public static void main(String[] args) {
int[] arr = {1,8,6,2,5,4,8,3,7};
System.out.println(maxArea1(arr));
}
/**
* 暴力法,寻找每一种可能
* @param height
* @return
*/
public static int maxArea1(int[] height) {
if(null == height || height.length == 0) {
return 0;
}
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
for (int j = 1; j < height.length ; j++) {
maxArea = Math.max(maxArea,Math.min(height[i],height[j])*(j-i));
}
}
return maxArea;
}
/**
* 这道题隐藏的条件是:两线段之间形成的区域总是会受到其中较短那条长度的限制。
* 此外,两线段距离越远,得到的面积就越大。
* @param height
* @return
*/
public static int maxArea2(int[] height) {
if(null == height || height.length == 0) {
return 0;
}
int maxArea = 0;
int l = 0;
int r = height.length-1;
while (l<r) {
maxArea = Math.max(maxArea,Math.min(height[l],height[r])*(r-l));
if(height[l]<height[r]) {
l++;
}else {
r++;
}
}
return maxArea;
}
}