Created
January 26, 2015 04:48
-
-
Save Maggie199/a0e51f8949f265ee26f1 to your computer and use it in GitHub Desktop.
Leetcode #42
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int trap(int[] A) { | |
int count = 0; | |
int leftPeak = -1; | |
int rightPeak = -1; | |
int minPeak = -1; | |
boolean flag = false; | |
for(int i=0; i<A.length; i++){ | |
if(isPeak(A,i)){ | |
leftPeak = rightPeak; | |
rightPeak = i; | |
if(leftPeak == -1) | |
continue; | |
else { | |
minPeak = Math.min(A[leftPeak],A[rightPeak]); | |
for(int j=leftPeak+1;j<rightPeak;j++){ | |
if(A[j]<minPeak){ | |
count += minPeak-A[j]; | |
A[j]=minPeak; | |
flag = true; | |
} | |
} | |
} | |
} | |
} | |
if(flag){ | |
count+= trap(A); | |
} | |
return count; | |
} | |
public boolean isPeak(int[] A, int i){ | |
if(i==0){ | |
if(i==A.length-1) | |
return false; | |
else if(A[i]>A[i+1]) | |
return true; | |
}else if(i==A.length-1){ | |
if(i==0) | |
return false; | |
else if(A[i]>A[i-1]) | |
return true; | |
}else if(A[i-1]<=A[i] && A[i]>=A[i+1]){ | |
if(A[i-1] == A[i] && A[i] == A[i+1]) | |
return false; | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment