๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์ž๋ฃŒ๊ตฌ์กฐ & ์•Œ๊ณ ๋ฆฌ์ฆ˜

K๋ฒˆ์งธ์ˆ˜ (Java)

by 1mj 2022. 2. 9.

https://programmers.co.kr/learn/courses/30/lessons/42748

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - K๋ฒˆ์งธ์ˆ˜

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ณ ๋“์  Kit ์ •๋ ฌ K๋ฒˆ์งธ์ˆ˜ ๋ฌธ์ œ ํ’€์ด์ด๋‹ค.

๋ฐฐ์—ด์—์„œ i๋ฒˆ์งธ๋ถ€ํ„ฐ j๋ฒˆ์งธ๊นŒ์ง€ ์ถ”์ถœํ•˜๊ณ  ์ •๋ ฌํ•œ ํ›„ k๋ฒˆ์งธ ๊ฐ’์„ ์ฐพ์œผ๋ฉด๋˜๋Š” ๋กœ์ง์ด ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์˜€๋‹ค.

 

# 1

์ฒซ ๋ฒˆ์งธ ํ’€์ด๋Š” ๋‹จ์ˆœํžˆ ๋ฐ˜๋ณต๋ฌธ ๋งŒ์„ ์ด์šฉํ•˜์—ฌ ๋ฐฐ์—ด์˜ ์ผ๋ถ€๋ฅผ ์ถ”์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€์—ˆ๋‹ค.

* Arrays.copyOfRange(array, i, j) ์ฒ˜๋Ÿผ ์ผ๋ถ€๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ž.

 

import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for (int idx = 0; idx < commands.length; idx++) {
            int i = commands[idx][0];
            int j = commands[idx][1];
            int k = commands[idx][2];
            
            List<Integer> targetList = new ArrayList<>();
            for (int temp = i - 1; temp < j; temp++) {
                targetList.add(array[temp]);
            }
            Collections.sort(targetList);
            
            answer[idx] = targetList.get(k-1);
        }
        return answer;
    }
}

 

ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ

 

# 2

๋‘ ๋ฒˆ์งธ ํ’€์ด๋Š” ๋ฐฐ์—ด์„ ์ถ”์ถœํ•˜๊ณ  ์ •๋ ฌํ•˜๋Š” ๊ฒƒ๊นŒ์ง€ ๋ชจ๋‘ ์ŠคํŠธ๋ฆผ์„ ํ™œ์šฉํ•œ ์ฝ”๋“œ์ด๋‹ค.

 

import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for (int idx = 0; idx < commands.length; idx++) {
            int i = commands[idx][0];   // i๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ
            int j = commands[idx][1];   // j๋ฒˆ์งธ ์ˆซ์ž๊นŒ์ง€ ์ž๋ฅด๊ณ 
            int k = commands[idx][2];   // k๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜ ๊ตฌํ•˜๊ธฐ
            
            answer[idx] = Arrays.stream(array, i-1, j)
                            .boxed()    // ์›์‹œํƒ€์ž…์„ ํด๋ž˜์Šคํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜
                            .sorted()   // ์ •๋ ฌ
                            .collect(Collectors.toList())   // ์ŠคํŠธ๋ฆผ์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ€ํ™˜
                            .get(k-1);  // ๋ฆฌ์ŠคํŠธ์˜ n๋ฒˆ์งธ ์š”์†Œ ๊ฐ€์ ธ์˜ค๊ธฐ
        }
        return answer;
    }
}

 

ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ

์ฝ”๋“œ๋Š” ๋‹จ์ˆœํ•ด์กŒ์ง€๋งŒ ์ŠคํŠธ๋ฆผ๋„ ๋‚ด๋ถ€์ ์œผ๋กœ๋Š” ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์–ด ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๋‹ค. ๋˜, ๋ฐฐ์—ด์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๊ณ  ์›์‹œ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„์„ ๋” ๋‹จ์ถ•ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๋Œ“๊ธ€