503.下一个更大元素II
思路:
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res,-1);
Deque<Integer> stack = new LinkedList<>();
//循环2遍数组,相当于拼接首尾
for(int i = 0; i < 2*n; i++){
while(!stack.isEmpty() && nums[stack.peek()] < nums[i % n]){
res[stack.peek()] = nums[i % n];
stack.pop();
}
stack.push(i % n);
}
return res;
}
}
需要注意的点:
42. 接雨水
思路:
代码:
双指针法,好理解,写得快
class Solution {
public int trap(int[] height) {
int res = 0;
for(int i = 0; i < height.length; i++){
//第一列和最后一列不用接
if(i == 0 || i == height.length - 1){
continue;
}
//找左侧和右侧最高的柱子
int left = height[i];
int right = height[i];
for(int j = i - 1; j >= 0; j--){
if(height[j] > left) left = height[j];
}
for(int j = i + 1; j < height.length; j++){
if(height[j] > right) right = height[j];
}
int h = Math.min(left, right) - height[i];
if(h > 0) res += h;
}
return res;
}
}