Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time Complexity: O(n)
- Space Complexity: O(n)
- n = length of nums array.
- */
- class Solution {
- public int[] nextGreaterElements(int[] nums) throws IllegalArgumentException {
- if (nums == null) {
- throw new IllegalArgumentException("Input nums array is null");
- }
- if (nums.length == 0) {
- return new int[0];
- }
- int len = nums.length;
- int[] result = new int[len];
- Arrays.fill(result, -1);
- Stack<Integer> stack = new Stack();
- for (int i = 0; i < len * 2; i++) {
- int num = nums[i % len];
- while (!stack.isEmpty() && nums[stack.peek()] < num) {
- result[stack.pop()] = num;
- }
- if (i < len) {
- stack.push(i);
- }
- }
- return result;
- }
- }
- /*
- Time Complexity: O(n)
- Space Complexity: O(n)
- n = length of nums array.
- */
- class Solution {
- public int[] nextGreaterElements(int[] nums) throws IllegalArgumentException {
- if (nums == null) {
- throw new IllegalArgumentException("Input nums array is null");
- }
- if (nums.length == 0) {
- return new int[0];
- }
- int len = nums.length;
- int[] result = new int[len];
- Stack<Integer> stack = new Stack();
- for (int i = len*2 -1; i >= 0; i--) {
- while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % len]) {
- stack.pop();
- }
- if (i < len) {
- result[i] = stack.isEmpty() ? -1 : nums[stack.peek()];
- }
- stack.push(i % len);
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement