LeetCode 503. Next Greater Element II

503. Next Greater Element II

Description Submission Solutions

  • Total Accepted: 3567
  • Total Submissions: 7703
  • Difficulty: Medium
  • Contributors: love_FDU_llp

 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.

Subscribe to see which companies asked this question.

【题目分析】

这个题目与前一个题目类似,不同的是数组中的元素可以组成一个圈,同样是找到某个元素右边第一个比他大的元素。

【思路】

这个题目同样是通过栈来解决,不过相比前一个题目,这个题目中的栈存储的是数组元素的下标。并且数组元素组成一个圈的话为了找出所有元素右边的最大值,我们需要把数组遍历两遍就足够了。由于在第一遍中所有元素都已经入栈,因此在第二遍的时候不需要再将元素入栈。

【java代码】

 1 public class Solution {
 2     public int[] nextGreaterElements(int[] nums) {
 3         int len = nums.length;
 4         int[] res = new int[len];
 5         Arrays.fill(res, -1);
 6         Stack<Integer> stack = new Stack<>();
 7         
 8         for(int i = 0; i < 2*len; i++) {
 9             int num = nums[i%len];
10             while(!stack.isEmpty() && nums[stack.peek()] < num) {
11                 res[stack.pop()] = num;
12             }
13             if(i < len) stack.push(i);
14         }
15         
16         return res;
17     }
18 }

 

posted @ 2017-02-21 11:59  Black_Knight  阅读(452)  评论(0编辑  收藏  举报