Next Greater Element II
给个数组A, 他是环状数组. 求一个数组B, B的每一个元素都是A中下一个比当前大的元素. 这个题和I其实差不多的做法, 也是用stack倒着存数组.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Solution { public int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] res = new int[nums.length]; Stack<Integer> st = new Stack<>(); Arrays.fill(res, -1); for(int i = 0; i < n*2; i++) { int num = nums[i%n]; while(!st.isEmpty()&&nums[st.peek()] < num) res[st.pop()] = num; if(i < n) st.push(i); } return res; } } |