[LeetCode] 503. 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.

 

题意:给一个循环数组,用另一个数组维护 第一个比当前数大的数字, 若不存在则为-1;

暴力法就不说了,我们用一个stack来维护下标

如果nums[s.peek()]的值小于nums[i], res[stack.peek()] = nums[i], s出栈,

循环两次,第一次全部的i都得进栈

第一次主要是找后面的,第二次则是找前面的;

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int[] res = new int[nums.length];
     
        for (int i = 0; i < nums.length; i++) 
            res[i] = -1;
        
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums.length; i++) {
            
            while (!stack.empty() && nums[stack.peek()] < nums[i])
                res[stack.pop()] = nums[i];
            
            stack.push(i);
        }
        for (int i = 0; i < nums.length; i++) {
            
            while (!stack.empty() && nums[stack.peek()] < nums[i])
                res[stack.pop()] = nums[i];
            
        }
        return res;
    }
}

 

posted @ 2018-10-07 20:14  C`Moriarty  阅读(94)  评论(0编辑  收藏  举报
/* 鼠标点击求赞文字特效 */ /*鼠标跟随效果*/