题目描述
解法一:暴力
时间复杂度:O(n^2),暴力竟然也能过!!
class Solution {
public int[] nextGreaterElements(int[] nums) {
//延长nums数组是原来的2倍
int[] nums1 = new int[nums.length * 2];
//复制
System.arraycopy(nums, 0, nums1, 0, nums.length);
System.arraycopy(nums, 0, nums1, nums.length, nums.length);
//暴力求解
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int j = i + 1;
while (j < nums1.length && nums1[j] <= nums1[i]) {
++j;
}
if(j == nums1.length){
//后面没有更大元素
res[i] = -1;
}else{
res[i] = nums1[j];
}
}
return res;
}
}
解法二:单调栈
class Solution {
public int[] nextGreaterElements(int[] nums) {
//延长nums数组是原来的2倍
int[] nums1 = new int[nums.length * 2];
//复制
System.arraycopy(nums, 0, nums1, 0, nums.length);
System.arraycopy(nums, 0, nums1, nums.length, nums.length);
int[] res = new int[nums.length]; //结果数组
Arrays.fill(res,-1); //默认是-1
Stack<int[]> stack = new Stack<>(); //单调栈,int[0]是nums1对应的下标,int[1]是值
//单调栈
for (int i = 0; i < nums1.length; i++) {
int num = nums1[i]; //当前元素
while (!stack.isEmpty() && stack.peek()[1] < num){
int[] pop = stack.pop();
if(pop[0] < nums.length){
res[pop[0]] = num;
}
}
stack.push(new int[]{i,num});
}
return res;
}
}