目录
LeetCode 503.下一个更大元素II
文章讲解:代码随想录
代码如下(Java):
class Solution {
public int[] nextGreaterElements(int[] nums) {
if(nums == null || nums.length <= 1) return new int[]{-1};
int size = nums.length;
int[] result = new int[size];
Arrays.fill(result, -1);
Stack<Integer> st = new Stack<>();
for(int i = 0; i < 2 * size; i++){
while(!st.empty() && nums[i % size] > nums[st.peek()]){
result[st.peek()] = nums[i % size];
st.pop();
}
st.push(i % size);
}
return result;
}
}
LeetCode 42.接雨水
文章讲解:代码随想录
力扣题目:LeetCode 42.接雨水
代码如下(java):
class Solution {
public int trap(int[] height) {
int sum = 0;
for(int i = 0; i < height.length; i++){
if(i == 0 || i == height.length - 1) continue;
int rHeight = height[i];
int lHeight = height[i];
for(int r = i + 1; r < height.length; r++){
if(height[r] > rHeight) rHeight = height[r];
}
for(int l = i-1; l >= 0; l--){
if(height[l] > lHeight) lHeight = height[l];
}
int h = Math.min(lHeight, rHeight) - height[i];
if(h > 0) sum += i;
}
return sum;
}
}