503. 下一个更大的元素II
题目链接:503. 下一个更大元素 II - 力扣(LeetCode)
class Solution {
public int[] nextGreaterElements(int[] nums) {
Deque<Integer> dq = new ArrayDeque<>();
int[] ans = new int[nums.length];
for(int i = 0; i < nums.length; ++i) {
ans[i] = -1;
if(dq.isEmpty()) {
dq.offerLast(i);
}else {
while(!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
ans[dq.pollLast()] = nums[i];
}
dq.offerLast(i);
}
}
for(int i = 0; i < nums.length; ++i) {
if(dq.isEmpty()) {
return ans;
}
while(!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
ans[dq.pollLast()] = nums[i];
}
}
return ans;
}
}
42. 接雨水
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int ret = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] < height[left + 1]) {
++left;
continue;
}
int x = height[left];
while (x >= height[left]) {
ret += (x - height[left]);
++left;
}
} else {
if (height[right] < height[right - 1]) {
--right;
continue;
}
int x = height[right];
while (left < right && x >= height[right]) {
ret += (x - height[right]);
--right;
}
}
}
return ret;
}
}