双指针
有这样一道题:
存水问题
package com.andong.demo.双指针.存水问题;
/**
* @Author andong
* @Date: 2021/04/10/21:36
* 存水问题
* @Description:
*/
public class TrappingRainWater {
public int trap(int[] height) {
if(height == null || height.length == 0) {
return 0;
}
int length = height.length;
int left = 0;
int right = length - 1;
int leftHeight = height[left];
int rightHeight = height[right];
int sum = 0;
while (left < right) {
if (leftHeight < rightHeight) {
if (leftHeight > height[left + 1]) {
sum += leftHeight - height[left + 1];
} else {
leftHeight = height[left +1];
}
left++;
} else {
if (rightHeight > height[right - 1]) {
sum += rightHeight - height[right - 1];
} else {
rightHeight = height[right - 1];
}
right--;
}
}
return sum;
}
public static void main(String[] args) {
}
}