-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathContainerWithMostWater.java
70 lines (70 loc) · 1.86 KB
/
ContainerWithMostWater.java
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
package io.ziheng.array.leetcode;
/**
* LeetCode 11. Container With Most Water
* https://leetcode.com/problems/container-with-most-water/
*/
public class ContainerWithMostWater {
public static void main(String[] args) {
int[] height = new int[]{1,8,6,2,5,4,8,3,7,};
int max = new ContainerWithMostWater().maxArea(height);
assert max == 49;
System.out.println("Test result: OK");
}
/**
* maxArea()
*
* @param height
* @return int
*/
public int maxArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
// return maxAreaLoop(height);
return maxAreaTwoPointer(height);
}
/**
* 双指针
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*
* @param height
* @return int
*/
private int maxAreaTwoPointer(int[] height) {
int max = 0;
for (int pLeft = 0, pRight = height.length - 1;
pLeft < pRight; /* ... */ ) {
int minHeight = 0;
if (height[pLeft] < height[pRight]) {
minHeight = height[pLeft];
pLeft++;
} else {
minHeight = height[pRight];
pRight--;
}
int area = (pRight - pLeft + 1) * minHeight;
max = Math.max(max, area);
}
return max;
}
/**
* 暴力迭代
* 时间复杂度:O(n^2)
* 空间复杂度:O(1)
*
* @param height
* @return int
*/
private int maxAreaLoop(int[] height) {
int max = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
int area = (j - i) * Math.min(height[i], height[j]);
max = Math.max(max, area);
}
}
return max;
}
}
/* EOF */