难度:中等
题目:给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例 1:
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
因为刚做了每日温度这道题,学会了单调栈的方法。所以遇到数组中求后面比它大还是比它小的数是谁,除了用暴力解法,又多了一种解法,使用单调栈。这道题也是一样的,不过需要注意的是,数组是循环数组,我们需要进行两轮操作。两轮操作后将栈中剩余的数置为-1.
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Stack<Integer> stack = new Stack<Integer>();//使用单调栈
for(int i=0;i<nums.length;i++){
//栈中存位置
int num = nums[i];
while(!stack.isEmpty() && num > nums[stack.peek()]){
int index = stack.pop();
res[index] = num;
}
stack.push(i);
}
for(int i=0;i<nums.length;i++){
while(!stack.isEmpty() && nums[i]>nums[stack.peek()]){
res[stack.pop()] = nums[i];
}
}
while(!stack.isEmpty()){
res[stack.pop()] = -1;
}
return res;
}
}
暴力解法:
public static int[] nextGreaterElements(int[] nums) {
// 构建用于记录结果的数组,初始化为-1
int res[] = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
res[i] = -1;
}
for (int i = 0; i < nums.length; i++) {
// 对于每一个元素i,向后遍历num.lenght长度
int count = 0;
int j = i + 1;
while (count < nums.length) {
// 对下标进行取模操作
j = j % nums.length;
if (nums[j] > nums[i]) {
res[i] = nums[j];
break;
}
j++;
count++;
}
}
return res;
}