Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7a9ca71

Browse files
edit 42
1 parent cc5efc4 commit 7a9ca71

File tree

2 files changed

+65
-26
lines changed

2 files changed

+65
-26
lines changed

src/main/java/com/fishercoder/solutions/_42.java

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,42 @@
1212

1313
public class _42 {
1414

15-
public int trap(int[] height) {
16-
int len = height.length;
17-
if (len == 0) {
18-
return 0;
15+
public static class Solution1 {
16+
/**O(n) time and O(1) space, awesome!*/
17+
/**reference: https://discuss.leetcode.com/topic/22976/my-accepted-java-solution*/
18+
public int trap(int[] height) {
19+
if (height == null || height.length <= 2) return 0;
20+
21+
int max = height[0];
22+
int maxIndex = 0;
23+
for (int i = 0; i < height.length; i++) {
24+
if (height[i] > max) {
25+
max = height[i];
26+
maxIndex = i;
27+
}
28+
}
29+
30+
int water = 0;
31+
32+
int leftMax = height[0];
33+
for (int i = 0; i < maxIndex; i++) {
34+
if (height[i] > leftMax) {
35+
leftMax = height[i];
36+
} else {
37+
water += leftMax - height[i];
38+
}
39+
}
40+
41+
int rightMax = height[height.length-1];
42+
for (int i = height.length-1; i > maxIndex; i--) {
43+
if (height[i] > rightMax) {
44+
rightMax = height[i];
45+
} else {
46+
water += rightMax - height[i];
47+
}
48+
}
49+
50+
return water;
1951
}
20-
int res = 0;
21-
22-
//first use DP to calculate left and right arrays
23-
int[] left = new int[height.length];
24-
int[] right = new int[height.length];
25-
26-
left[0] = height[0];
27-
for (int i = 1; i < height.length; i++) {
28-
left[i] = Math.max(left[i - 1], height[i]);
29-
}
30-
31-
right[height.length - 1] = height[height.length - 1];
32-
for (int i = height.length - 2; i >= 0; i--) {
33-
right[i] = Math.max(right[i + 1], height[i]);
34-
}
35-
36-
for (int i = 1; i < height.length - 1; i++) {
37-
res += Math.min(left[i], right[i]) - height[i];
38-
}
39-
return res;
4052
}
41-
42-
}
53+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._42;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
/**
10+
* Created by fishercoder on 5/13/17.
11+
*/
12+
public class _42Test {
13+
private static _42.Solution1 solution1;
14+
private static int[] height;
15+
16+
@BeforeClass
17+
public static void setup(){
18+
solution1 = new _42.Solution1();
19+
}
20+
21+
@Test
22+
public void test1(){
23+
height = new int[]{0,1,0,2,1,0,1,3,2,1,2,1};
24+
assertEquals(6, solution1.trap(height));
25+
}
26+
27+
28+
}

0 commit comments

Comments
 (0)