我的题解
两层for循环
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < i + nums.length; j++){
if(nums[i] < nums[j % nums.length]){
res[i] = nums[j % nums.length];
break;
}
}
}
return res;
}
}
优秀题解
思路:单调栈
- 单调栈里只需要存放元素的下标i就可以了,如果需要使用对应的元素,直接T[i]就可以获取。
- 在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是整个数组只需要遍历一次。
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
Stack<Integer> st= new Stack<>();
for(int i = 0; i < 2 * nums.length; i++){
while(!st.isEmpty() && nums[i % nums.length] > nums[st.peek()]){
res[st.peek()] = nums[i % nums.length];
st.pop();
}
st.push(i % nums.length);
}
return res;
}
}