对数组中的每一个元素,找出他后面第几个数比自己大
给定一个列表[73, 74, 75, 71, 69, 72, 76, 73],输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
public class Test001 { public static void main(String[] args) { Integer [] arr = new Integer [] {73, 74, 75, 71, 69, 72, 76, 73}; Stack<Integer> stack = new Stack<Integer>(); Integer [] res = new Integer[arr.length]; for(int i = 0 ; i<arr.length ; i++) { while(!stack.isEmpty() && arr[i] > arr[stack.peek()]) { int index = stack.pop(); res[index] = i - index; } stack.push(i); } while(!stack.isEmpty()) { res[stack.pop()] = 0 ; } Arrays.stream(res).forEach(x -> System.out.print(x + " ")); } }

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号