[LeetCode] 503. Next Greater Element II

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

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, return -1 for this number.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]

Constraints:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

下一个更大的元素II。

给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。

数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

版本一传送门在此。这个题依然是找数组中往右比当前元素更大的元素,但是版本二改了一个设定,需要假设 input 是一个环,也就是说数组最后一个元素在 res 里面的结果很有可能不是-1。

思路依然是单调栈,去看栈顶元素是否比当前元素小,若栈顶元素小则弹出栈并存到结果集 res 里面;若栈顶元素大则还是把当前元素的 index 入栈。单调栈类型的题绝大部分放入栈的都是遍历数组的 index,但是这道题因为是环的关系,所以需要遍历两遍 input 数组,但是注意元素入栈只有一次。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] nextGreaterElements(int[] nums) {
 3         int n = nums.length;
 4         int[] res = new int[n];
 5         Arrays.fill(res, -1);
 6         Deque<Integer> stack = new ArrayDeque<>();
 7         for (int i = 0; i < n * 2; i++) {
 8             int cur = nums[i % n];
 9             while (!stack.isEmpty() && cur > nums[stack.peekLast() % n]) {
10                 int index = stack.pollLast();
11                 res[index % n] = cur;
12             }
13             stack.offerLast(i);
14         }
15         return res;
16     }
17 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[]}
 4  */
 5 var nextGreaterElements = function (nums) {
 6     let len = nums.length;
 7     let res = new Array(len).fill(-1);
 8     let stack = [];
 9     for (let i = 0; i < nums.length * 2; i++) {
10         let cur = nums[i % len];
11         while (stack.length > 0 && nums[stack[stack.length - 1]] < cur) {
12             res[stack.pop()] = cur;
13         }
14         if (i < len) {
15             stack.push(i);
16         }
17     }
18     return res;
19 };

 

LeetCode 题目总结

posted @ 2020-03-16 02:22  CNoodle  阅读(198)  评论(0)    收藏  举报