java: add «42. Trapping Rain Water»
URL: https://leetcode.com/problems/trapping-rain-water/
This commit is contained in:
parent
b12e923384
commit
9608f3259b
1 changed files with 20 additions and 0 deletions
20
java/trapping-rain-water.java
Normal file
20
java/trapping-rain-water.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
class Solution {
|
||||
public int trap(int[] height) {
|
||||
var caught = 0;
|
||||
|
||||
int i = 0, j = height.length - 1;
|
||||
int maxLeft = height[i], maxRight = height[j];
|
||||
while (i < j) {
|
||||
maxLeft = Math.max(maxLeft, height[i]);
|
||||
maxRight = Math.max(maxRight, height[j]);
|
||||
|
||||
if (maxLeft < maxRight) {
|
||||
caught += maxLeft - height[i++];
|
||||
} else {
|
||||
caught += maxRight - height[j--];
|
||||
}
|
||||
}
|
||||
|
||||
return caught;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue