[알고리즘] 인프런 - K번째 큰 수

정은아·2024년 1월 9일
post-thumbnail

인프런 - 자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

- Section 4 - K번째 큰 수 문제

내 풀이

import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class HashMap_05 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		int k = sc.nextInt();
		int [] num = new int [n];
		
		for (int i = 0; i < n; i++) {
			num[i] = sc.nextInt();
		}
		
		int answer = -1;
		int cnt = 0;
		
		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(num[i] + num[j] + num[l]);
				}
			}
		}
		
		for (Integer x : Tset) {
			cnt++;
			if (cnt == k) {
				answer = x;
				break;
			}
		}
		
		System.out.println(answer);
	}
}

느낀점

for문 돌릴 때 범위 설정을 똑바로 하자!!!

profile
꾸준함의 가치를 믿는 개발자

0개의 댓글