Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 4, 2015 20:28
Show Gist options
  • Save cangoal/6315fccf676715ef75ee to your computer and use it in GitHub Desktop.
Save cangoal/6315fccf676715ef75ee to your computer and use it in GitHub Desktop.
LeetCode - Trapping Rain Water
//
public int trap(int[] height) {
if(height == null || height.length <= 2) return 0;
int left = 0, right = height.length - 1, sum = 0, h = 0;
while(left < right){
if(height[left] <= height[right]){
if(height[left] < h){
sum += h - height[left];
}
h = Math.max(h, height[left]);
left++;
} else {
if(height[right] < h){
sum += h - height[right];
}
h = Math.max(h, height[right]);
right--;
}
}
return sum;
}
//
public int trap(int[] A) {
//Solution 2: Scan only one time
if(A==null || A.length<=2) return 0;
int left=0, right = A.length-1, leftMax=0, rightMax=0, max=0;
while(left<=right){
//move left bar toward right
if(leftMax<=rightMax){
if(leftMax-A[left]>0)
max += leftMax-A[left];
leftMax = Math.max(leftMax, A[left]);
left++;
}else{
//move right bar toward left
if(rightMax-A[right]>0)
max += rightMax-A[right];
rightMax = Math.max(rightMax, A[right]);
right--;
}
}
return max;
}
//
public int trap(int[] A) {
//Solution 1: scan twice
if(A==null || A.length<3) return 0;
int leftMax=A[0], rightMax=A[A.length-1], max=0;
int[] ret = new int[A.length];
for(int i=1; i<A.length-1; i++){
ret[i] = leftMax;
leftMax = Math.max(leftMax, A[i]);
}
for(int i=A.length-2; i>0; i--){
if(Math.min(rightMax, ret[i])-A[i]>0){
max += Math.min(rightMax, ret[i]) - A[i];
}
rightMax = Math.max(rightMax, A[i]);
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment