LeetCode 503. Next Greater Element II
原题链接在这里:https://leetcode.com/problems/next-greater-element-ii/
题目:
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
Note: The length of given array won't exceed 10000.
题解:
一般这类带环的一种常见做法是加长一倍. 这里就是把nums 走两边.
没用HashMap<Integer, Integer>是因为nums里会有duplicate. 这里的Stack<Integer> stk 存的是element index 而不是element, 需要index来填res.
Time Complexity: O(n), n = nums.length.
Space: O(n), res size.
AC Java:
1 class Solution { 2 public int[] nextGreaterElements(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return nums; 5 } 6 7 Stack<Integer> stk = new Stack<>(); 8 int n = nums.length; 9 int [] res = new int[n]; 10 for(int i = 2 * n - 1; i >= 0; i--){ 11 int ind = i % n; 12 while(!stk.isEmpty() && nums[stk.peek()] <= nums[ind]){ 13 stk.pop(); 14 } 15 16 if(i < n){ 17 res[ind] = stk.isEmpty() ? -1 : nums[stk.peek()]; 18 } 19 20 stk.push(ind); 21 } 22 23 return res; 24 } 25 }
We could also iterate from left to right and have monotonic increasing stack. When encounter current element x is bigger, update all the popped index element next greater as x.
Then push ind = i % n in the stack.
Time Complexity: O(n).
Space: O(n).
AC Java:
1 class Solution { 2 public int[] nextGreaterElements(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return nums; 5 } 6 7 int n = nums.length; 8 int [] res = new int[n]; 9 Arrays.fill(res, -1); 10 Stack<Integer> stk = new Stack<>(); 11 for(int i = 0; i < 2 * n; i++){ 12 int ind = i % n; 13 while(!stk.isEmpty() && nums[stk.peek()] < nums[ind]){ 14 res[stk.pop()] = nums[ind]; 15 } 16 17 stk.push(ind); 18 } 19 20 return res; 21 } 22 }
AC C++:
1 class Solution { 2 public: 3 vector<int> nextGreaterElements(vector<int>& nums) { 4 int n = nums.size(); 5 vector<int> res(n, -1); 6 stack<int> stk; 7 8 for(int i = 0; i < n * 2; i++){ 9 int ind = i % n; 10 while(!stk.empty() && nums[stk.top()] < nums[ind]){ 11 int top = stk.top(); 12 stk.pop(); 13 res[top] = nums[ind]; 14 } 15 16 stk.push(ind); 17 } 18 19 return res; 20 } 21 };
AC Python:
1 class Solution: 2 def nextGreaterElements(self, nums: List[int]) -> List[int]: 3 n = len(nums) 4 stk = [] 5 res = [-1] * n 6 for i in list(range(n)) * 2: 7 while stk and nums[stk[-1]] < nums[i]: 8 res[stk.pop()] = nums[i] 9 stk.append(i) 10 return res