[백준 17298] 오큰수
- 💾 알고리즘/LeetCode_백준
- 2022. 9. 26. 12:47
🔗 문제
https://www.acmicpc.net/problem/17298
📝 풀이
- 스택에 첫 index 값을 넣고 peek로 배열의 값을 비교해가면서 큰 수를 넣고, 배열으 전체 순회 후, 정답배열에 남아있는 index에 -1 넣어준다.
💻 코드
package org.kyhslam.bakjun;
import java.io.*;
import java.util.Scanner;
import java.util.Stack;
public class p17298 {
public static void main(String[] args) throws IOException {
// 4
// Q: 3 5 2 7
// A: 5 7 7 -1
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
//int N = sc.nextInt();
int N = Integer.parseInt(bf.readLine());
int[] A = new int[N];
int[] ans = new int[N];
String[] str = bf.readLine().split(" ");
for (int i = 0; i < N; i++) {
A[i] = Integer.parseInt(str[i]);
}
Stack<Integer> myStack = new Stack<>();
myStack.push(0);
for (int i = 1; i < A.length; i++) {
while( !myStack.isEmpty() && A[i] > A[myStack.peek()]) {
ans[myStack.pop()] = A[i];
}
myStack.push(i);
}
while( !myStack.isEmpty() ) {
ans[myStack.pop()] = -1;
}
//출력
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for(int i=0; i < N; i++){
bw.write(ans[i] + " ");
}
bw.write("\n");
bw.close();
}
}
'💾 알고리즘 > LeetCode_백준' 카테고리의 다른 글
[백준 17298] ATM (삽입정렬 사용) (0) | 2022.11.01 |
---|---|
[백준 1377] 버블 소트 (0) | 2022.11.01 |
[백준 1940] 주몽 - 투 포인터 (0) | 2022.06.27 |
[백준 11660] 구간 합 구하기 5 (0) | 2022.06.22 |
[LeetCode] 561. Array Partition I (0) | 2022.06.07 |