ALGORITHM
[JAVA] 알고리즘 : TreeSet - k번째 큰 수
연듀
2022. 7. 6. 09:54
import java.util.*;
class Main {
public int solution(int[] arr, int n, int k) {
int answer = -1;
TreeSet<Integer> Tset = new TreeSet<>(Collections.reverseOrder());
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
for(int l=j+1; l<n; l++){
Tset.add(arr[i]+arr[j]+arr[l]);
}
}
}
int cnt=0;
for(int x : Tset){
cnt++;
if(cnt==k) return x;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i]=sc.nextInt();
}
System.out.println(T.solution(arr, n, k));
}
}
Treeset: 중복 제거, 정렬 가능
기본적으로 오름차순이고 Collections.reverseOrder()를 하면 내림차순이 된다.
삼중 for문을 돌며 3개의 경우의 수를 뽑아 Treeset 자료구조에 추가한다. 이 때 중복되면 안되므로 안의 for문은 바깥 for문의 첫번째 원소 그 다음부터 시작한다.
그리고 추가된 Treeset의 k번째수를 구한다.
반응형