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.
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int le = nums.length;
        int[] arr = new int[le * 2];
        int[] res = new int[le];
        Arrays.fill(res, -1);
        if(le == 0 || nums == null) return new int[0];
        for(int i = 0; i < le; i++) arr[i] = nums[i];
        for(int i = le; i < 2 * le; i++) arr[i] = nums[i - le];
        for(int i = 0; i < le; i++){
            for(int j = i + 1; j < 2 * le; j++){
                if(arr[j] > nums[i]){ res[i] = arr[j]; break;}
                
            }
        }
        return res;
    }
}

扩充下数组即可

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        Stack<Integer> stack = new Stack();
        int res[] = new int[n];
        Arrays.fill(res, -1);
        
        for(int i = 0; i < 2 * n; i++) {
            int cur = nums[i % n];
            while(!stack.isEmpty() && nums[stack.peek()] < cur) {
                res[stack.pop()] = cur;
            }
            if(i < n) stack.push(i);
        }
        return res;
    }
}

用stack存放decreasing subsequence的index,如果对应的num小于当前的cur,说明cur就是next greater。记得初始化-1。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11955510.html