BiruLyu
7/3/2017 - 4:26 AM

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;
    }
}