|
1 | 1 | package org.gd.leetcode.p0011; |
2 | 2 |
|
3 | | -import org.gd.leetcode.common.Repeat; |
4 | 3 | import org.gd.leetcode.common.LeetCode; |
| 4 | +import org.gd.leetcode.common.Repeat; |
5 | 5 |
|
6 | 6 | /** |
7 | | - * https://leetcode.com/problems/container-with-most-water/ |
| 7 | + * <a href="https://leetcode.com/problems/container-with-most-water/">LeetCode #11: Container With Most Water</a> |
| 8 | + * |
| 9 | + * @see org.gd.leetcode.p0042.Solution |
8 | 10 | */ |
9 | 11 | @Repeat |
10 | 12 | @LeetCode( |
|
15 | 17 | LeetCode.Tags.ARRAY, |
16 | 18 | LeetCode.Tags.TWO_POINTERS |
17 | 19 | }) |
| 20 | +@SuppressWarnings("JavadocReference") |
18 | 21 | class Solution { |
19 | 22 |
|
20 | | - private static int max(int i1, int i2, int i3) { return Math.max(i1, Math.max(i2, i3)); } |
| 23 | + public int maxArea(int[] heights) { |
| 24 | + if (heights == null || heights.length < 2) { |
| 25 | + return 0; |
| 26 | + } |
21 | 27 |
|
22 | | - public int maxArea(int[] height) { |
23 | | - switch (height.length) { |
24 | | - case 0: |
25 | | - case 1: return 0; |
26 | | - case 2: return Math.min(height[0], height[1]); |
27 | | - case 3: return max(height[0], height[1], height[2]); |
| 28 | + if (heights.length == 2) { |
| 29 | + return Math.max(0, Math.min(heights[0], heights[1])); |
28 | 30 | } |
29 | | - int i = 0, j = height.length - 1, max = Integer.MIN_VALUE, h; |
30 | | - while (i < j) { |
31 | | - max = Math.max(max, (j - i) * (h = Math.min(height[i], height[j]))); |
32 | | - while (height[i] <= h && i < j) i++; |
33 | | - while (height[j] <= h && i < j) j--; |
| 31 | + |
| 32 | + int leftIndex = 0; |
| 33 | + int rightIndex = heights.length - 1; |
| 34 | + int max = 0; |
| 35 | + while (leftIndex < rightIndex) { |
| 36 | + int height = Math.min(heights[leftIndex], heights[rightIndex]); |
| 37 | + int width = rightIndex - leftIndex; |
| 38 | + max = Math.max(max, width * height); |
| 39 | + while (heights[leftIndex] <= height && leftIndex < rightIndex) { |
| 40 | + leftIndex++; |
| 41 | + } |
| 42 | + while (heights[rightIndex] <= height && leftIndex < rightIndex) { |
| 43 | + rightIndex--; |
| 44 | + } |
34 | 45 | } |
35 | 46 | return max; |
36 | 47 | } |
|
0 commit comments