๊ธฐ๋ก๋ฐฉ

BOJ_11004 : K๋ฒˆ์žฌ ์ˆ˜ ๋ณธ๋ฌธ

CodingTest/Java

BOJ_11004 : K๋ฒˆ์žฌ ์ˆ˜

Soom_1n 2022. 10. 25. 23:30

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

11004๋ฒˆ: K๋ฒˆ์งธ ์ˆ˜

์ˆ˜ N๊ฐœ A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. A๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ–ˆ์„ ๋•Œ, ์•ž์—์„œ๋ถ€ํ„ฐ K๋ฒˆ์งธ ์žˆ๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • ์ž…๋ ฅ๋ฐ›์€ N๊ฐœ์˜ ์ˆ˜๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ–ˆ์„๋•Œ K๋ฒˆ์žฌ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
  • N์ด ์ตœ๋Œ€ 5,000,000(5๋ฐฑ๋งŒ)์ด๋ฏ€๋กœ, O(nlogn)์€ ์•ฝ 3์ฒœ๋งŒ์ด ๋‚˜์˜จ๋‹ค.
    • ์ผ๋ฐ˜์ ์ธ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ํ‰๊ท  ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(nlogn)์ด๋ฏ€๋กœ, ์ œํ•œ์‹œ๊ฐ„ 2์ดˆ์•ˆ์— ๋“ ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        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 arr[] = new int[n];

        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++){
            arr[i] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(arr);

        System.out.println(arr[k-1]);
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • n๊ฐœ์˜ ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋ฐฐ์—ด arr์— ์ €์žฅํ•œ๋‹ค.
  • ๋ฐฐ์—ด arr๋ฅผ Arrays.sort()๋ฅผ ์‚ฌ์šฉํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.
  • ๋ฐฐ์—ด arr์˜ k๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ๊ฒฐ๊ณผ์ ์œผ๋กœ ์ตœ์ข… ์ฝ”๋“œ์—์„œ ์•„์ฃผ ๋‹จ์ˆœํ•œ ๋ฐฐ์—ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ์‚ฌ์šฉํ•ด๋„ ํ†ต๊ณผํ–ˆ์ง€๋งŒ,
    O(n^2)์ธ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์„๊นŒ๋ด ์นด์šดํŠธ ์ •๋ ฌ๋ฅผ ์จ์•ผ๋˜๋Š” ์ค„ ์•Œ๊ณ  ์˜ค๋‹ต์ด ๋Š˜์—ˆ๋‹ค.
    • ์ด ๋ฌธ์ œ์—์„œ O(n^2)์ด๋ฉด, 25,000,000,000,000(25์กฐ)์ด๋ฏ€๋กœ ์ œํ•œ์‹œ๊ฐ„์„ ํ›จ์”ฌ ๋„˜๊ฒŒ๋œ๋‹ค.
    • ๋”ฐ๋ผ์„œ ์—ฐ์‚ฐ ํšŸ์ˆ˜๋ฅผ ์ค„์ด๊ธฐ ์œ„ํ•ด ์นด์šดํŠธ ์ •๋ ฌ์„ ์‚ฌ์šฉํ•˜๋ ค๊ณ  ํ–ˆ๋‹ค.
    • ํ•˜์ง€๋งŒ ์ˆ˜์˜ ๋ฒ”์œ„๊ฐ€ -10^9 ~ 10^9 ์ด๋ฏ€๋กœ ์ž๋ฐ”์˜ ๋ฐฐ์—ด ๋ฒ”์œ„๋ฅผ ๋„˜๊ฒŒ๋˜์„œ ๋ถˆ๊ฐ€๋Šฅํ–ˆ๋‹ค.
    • ์•Œ์•„๋ณด๋‹ˆ ์ด ๋ฌธ์ œ๋Š” N๊ฐœ์˜ ์ˆ˜์—์„œ K๋ฒˆ์งธ ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉ๋˜๋Š” ํŠน์ •ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ธ
      Quick Selection ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค. Quick sort๋ฐฉ์‹์„ ์‘์šฉํ•œ ๋ฐฉ์‹์ด๋‹ค.

728x90