이중 반복문
import java.util.Arrays;
public class Baek17298 {
public static void main(String[] args) {
int[] input = {3,5,2,7};
int[] result = new int[4];
Arrays.fill(result,-1);
for(int i=0;i<4;i++){
for(int j=i+1;j<4;j++){
if(input[i]<input[j]){
result[i]=input[j];
break;
}
}
}
for(int k : result) System.out.println(k);
}
}
스택이용
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
public class Baek17298 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
int[] answer = new int[N];
Arrays.fill(answer, -1);
StringTokenizer st = new StringTokenizer(sc.nextLine());
Stack<int[]> stack = new Stack<>();
for(int i=0;i<N;i++) {
int val=Integer.parseInt(st.nextToken());
if(stack.size()==0) stack.push(new int[] {val,i});
else {
if(stack.peek()[0]>val) stack.push(new int[] {val,i});
else {
while(stack.size()>0&&stack.peek()[0]<val) answer[stack.pop()[1]]=val;
stack.push(new int[] {val,i});
}
}
}
for(int i=0;i<N;i++) System.out.print(answer[i]+" ");
}
}