题目:给定一个整型数组,数组元素随机无序的,要求打印出所有元素右边第一个大于该元素的值。
如数组A=[1,5,3,6,4,8,9,10] 输出[5, 6, 6, 8, 8, 9, 10, -1]
如数组A=[8, 2, 5, 4, 3, 9, 7, 2, 5] 输出[9, 5, 9, 9, 9, -1, -1, 5, -1]
import java.util.Scanner;
import java.util.Stack;
public class no26 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] chs = in.nextLine().replaceAll(",", "").toCharArray();
int[] arr = new int[chs.length];
for (int i = 0; i < chs.length; i++) {
arr[i] = chs[i]-'0';
}
int[] ans = findMaxRightWithStack(arr);
for(int i:ans){
System.out.print(i+",");
}
}
static int[] findMaxRightWithStack(int[] arr) {
if (arr == null) {
return arr;
}
int len= arr.length;
int[] result = new int[len];
Stack<Integer> stack = new Stack<>();
stack.push(0);
int index = 1;
while(index<len){
if (!stack.isEmpty() && arr[stack.peek()] < arr[index]) {
result[stack.pop()] = arr[index];
} else {
stack.push(index);
index++;
}
}
while (!stack.isEmpty()) {
result[stack.pop()] = -1;
}
return result;
}
}