day59
1、leetcode503 下一个更大元素Ⅱ
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
Deque<Integer> dq = new ArrayDeque<>();
for(int i=0; i<nums.length*2; i++) {
while(!dq.isEmpty() && nums[dq.peekLast()]<nums[i%nums.length]) {
int index = dq.pollLast();
res[index] = nums[i%nums.length];
}
dq.addLast(i%nums.length);
}
return res;
}
}
2、leetcode42 接雨水
-
当前列雨水面积:min(左边柱子的最高高度,记录右边柱子的最高高度) - 当前柱子高度。
-
代码
class Solution { public int trap(int[] height) { int leftMax = 0; int rightMax = 0; int rainSum = 0; for(int i=0; i<height.length; i++) { if(i==0 || i==height.length-1) { continue; } leftMax = height[i]; for(int l=i-1; l>=0; l--) { leftMax = Math.max(leftMax, height[l]); } rightMax = height[i]; for(int r=i+1; r<height.length; r++) { rightMax = Math.max(rightMax, height[r]); } rainSum += (Math.min(leftMax, rightMax)-height[i]); } return rainSum; } }

浙公网安备 33010602011771号