题目:
https://leetcode-cn.com/problems/next-greater-element-ii/
解法一:
for循环暴力求解,从数组当前元素开始,向后遍历寻找下一个更大元素,可利用取模实现循环数组。时间复杂度:O(N^2)
public int[] nextGreaterElements(int[] nums) {
int length = nums.length;
int[] answerArr = new int[length];
for (int i = 0; i < nums.length; i++) {
int temp = -1;
for (int j = i + 1; j < length + i; j++) {
if (nums[j%length] > nums[i]) {
temp = nums[j%length];
break;
}
}
answerArr[i] = temp;
}
return answerArr;
}
解法二:
构建一个单调递增栈,栈中存放数组下标,时间复杂度:O(N)
public int[] nextGreaterElements(int[] nums) {
int length = nums.length;
int[] answerArr = new int[length];
Arrays.fill(answerArr, -1);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < length * 2; i++) {
while (!stack.isEmpty() && nums[i%length] > nums[stack.peek()]) {
answerArr[stack.pop()] = nums[i%length];
}
stack.push(i%length);
}
return answerArr;
}
本题虽然使用暴力求解也能AC,但是最优方案还是需要使用单调栈。