高级农民
- 积分
- 2263
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-5-5
- 最后登录
- 1970-1-1
|
05/01/2019 Day46
LeetCode 42. Trapping Rain Water
Importantce【5】
解题思路:
双指针的题目。
主要是考虑每一个位置可以存的水的体积是 min{leftMax, rightMax} - height[i]
- class Solution {
- public int trap(int[] height) {
- // time: O(n) 99.85%
- // space: O(1) 89.09%
- int res = 0;
- if (height == null || height.length == 0) return res;
-
- int left = 0, right = height.length - 1;
- int leftMax = 0, rightMax = 0;
- while (left < right) {
- if (height[left] < height[right]) { // height[right] <= rightMax_before
- leftMax = Math.max(leftMax, height[left]);
- res += leftMax - height[left];
- left++;
- } else {
- rightMax = Math.max(rightMax, height[right]);
- res += rightMax - height[right];
- right--;
- }
- }
- return res;
- }
- }
复制代码 |
|