
난이도: ★☆☆☆☆ • solved on: 2025-12-26

자료구조
PriorityQueue<Integer> (최대 힙처럼 사용)int[] 배열알고리즘/기법
핵심 키워드
- 문제 분해
- 모든 점수를 우선순위 큐(내림차순)로 넣는다.
poll()을 K-1번 수행하면, 다음poll()이 K번째로 큰 점수이다.
핵심 로직 흐름
maxHeap에 모든 점수 삽입 (k-1)번 poll 다음 poll 값 출력예외 처리
- 없음 (K는 1 이상, N 이하)
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] cmds = sc.nextLine().split(" ");
int n = Integer.parseInt(cmds[0]);
int k = Integer.parseInt(cmds[1]);
String[] nums = sc.nextLine().split(" ");
PriorityQueue<Integer> q = new PriorityQueue<>(Comparator.reverseOrder());
for(String num : nums) {
q.add(Integer.valueOf(num));
}
for(int i = 0; i < k-1; i++){
q.poll();
}
System.out.println(q.poll());
}
}
- 문제 분해
- 점수를 배열에 담고
Arrays.sort()로 오름차순 정렬한다.- 오름차순에서 N-K 인덱스가 “내림차순 K번째”와 동일하다.
핵심 로직 흐름
scores 정렬(오름차순) 출력 = scores[n - k]예외 처리
- 없음
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] a = new int[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken());
Arrays.sort(a); // 오름차순
System.out.println(a[n - k]); // 내림차순 K번째
}
}
점수의 최댓값 범위가 크지 않으면 (이 문제는 점수 범위가 작게 주어지는 편) 정렬 없이도 가능하다.
- 점수별 빈도를
count[score]에 저장- 큰 점수부터 내려오며 누적합이 K 이상이 되는 순간의 점수가 정답
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
// 점수 범위가 0~10000이라고 가정(문제 조건에 맞춰 배열 크기 설정)
int[] cnt = new int[10001];
st = new StringTokenizer(br.readLine());
int max = 0;
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(st.nextToken());
cnt[x]++;
if (x > max) max = x;
}
int acc = 0;
for (int score = max; score >= 0; score--) {
acc += cnt[score];
if (acc >= k) {
System.out.println(score);
return;
}
}
}
}
방법 1 (PriorityQueue)
방법 2 (정렬)
방법 3 (카운팅)
비슷한 유형 (GPT 추천) :
확장 문제 (GPT 추천) :