java 503. Next Greater Element II(1st).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 503. Next Greater Element II(1st).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    
    public int[] nextGreaterElements(int[] nums) {
        if (nums == null || nums.length < 1) return new int[0];
        int len = nums.length;
        int[] res = new int[len];
        Arrays.fill(res, -1);
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < len * 2; i++) {
            int num = nums[i % len];
            while (!stack.isEmpty() && num > nums[stack.peek()]) {
                res[stack.pop()] = num;
            }
            if (i < len) {
                stack.push(i);
            }
        }
        return res;
    }
}
public class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if(nums.length == 0)
    		return nums;
    	int max = Integer.MIN_VALUE,index = -1;
        for(int i = 0;i<nums.length;i++){
        	if(max<nums[i]){
        		max = nums[i];
        		index = i;
        	}
        }
        int[] res = new int[nums.length];
        res[index] = -1;
        for(int i=index-1;i != index;i--){
        	if(i == -1)
        		i = nums.length -1;
        	if(i == index)
        		break;
        	int j = i+1;
        	if(j >= nums.length){
        		j = 0;
        	}
        	while(nums[i]>=nums[j] && nums[j]!=max){
        		j = res[j];
        		if(j >= nums.length){
            		j = 0;
            	}
        	}
        	if(nums[i] == max)
        		res[i] = -1;
        	else
        		res[i] = j;	
        	
        	
        }
        int[] Greater = new int[res.length];
    	for(int i=0;i<res.length;i++){
    		if(res[i] == -1)
    			Greater[i] = -1;
    		else
    			Greater[i] = nums[res[i]];
    	}
        return Greater;
    }
}

以上是关于java 503. Next Greater Element II(1st).java的主要内容,如果未能解决你的问题,请参考以下文章

java 503. Next Greater Element II(1st).java

java 503. Next Greater Element II(1st).java

java 503. Next Greater Element II(1st).java

java 503. Next Greater Element II(1st).java

Leetcode 503. Next Greater Element II JAVA语言

503. Next Greater Element II