Advertisement
1988coder

503. Next Greater Element II

Dec 24th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. /*
  2. Time Complexity: O(n)
  3. Space Complexity: O(n)
  4.  
  5. n = length of nums array.
  6. */
  7. class Solution {
  8.     public int[] nextGreaterElements(int[] nums) throws IllegalArgumentException {
  9.         if (nums == null) {
  10.             throw new IllegalArgumentException("Input nums array is null");
  11.         }
  12.        
  13.         if (nums.length == 0) {
  14.             return new int[0];
  15.         }
  16.        
  17.         int len = nums.length;
  18.         int[] result = new int[len];
  19.         Arrays.fill(result, -1);
  20.         Stack<Integer> stack = new Stack();
  21.        
  22.         for (int i = 0; i < len * 2; i++) {
  23.             int num = nums[i % len];
  24.             while (!stack.isEmpty() && nums[stack.peek()] < num) {
  25.                 result[stack.pop()] = num;
  26.             }
  27.             if (i < len) {
  28.                 stack.push(i);
  29.             }
  30.         }
  31.        
  32.         return result;
  33.     }
  34. }
  35.  
  36.  
  37. /*
  38. Time Complexity: O(n)
  39. Space Complexity: O(n)
  40.  
  41. n = length of nums array.
  42. */
  43. class Solution {
  44.     public int[] nextGreaterElements(int[] nums) throws IllegalArgumentException {
  45.         if (nums == null) {
  46.             throw new IllegalArgumentException("Input nums array is null");
  47.         }
  48.        
  49.         if (nums.length == 0) {
  50.             return new int[0];
  51.         }
  52.        
  53.         int len = nums.length;
  54.         int[] result = new int[len];
  55.         Stack<Integer> stack = new Stack();
  56.        
  57.         for (int i = len*2 -1; i >= 0; i--) {
  58.             while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % len]) {
  59.                 stack.pop();
  60.             }
  61.             if (i < len) {
  62.                 result[i] = stack.isEmpty() ? -1 : nums[stack.peek()];
  63.             }
  64.             stack.push(i % len);
  65.         }
  66.        
  67.         return result;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement