Contents

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

   Jun 8, 2024     2 min read

โ€œK๋ฒˆ์งธ์ˆ˜ (with.Java)โ€ ๋ฌธ์ œ์— ๋Œ€ํ•˜์—ฌ ์•Œ์•„๋ณธ ๊ธ€์ž…๋‹ˆ๋‹ค.

์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉฐ, ํ’€์—ˆ๋˜ ๋ฌธ์ œ์— ๋Œ€ํ•œ ํšŒ๊ณ ์™€ ๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋ฉฐ, ์•Œ์•„๊ฐ€๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ์— ๋Œ€ํ•ด ๋จผ์ € ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๋ฌธ์ œ

๋ฐฐ์—ด array์˜ i๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ j๋ฒˆ์งธ ์ˆซ์ž๊นŒ์ง€ ์ž๋ฅด๊ณ  ์ •๋ ฌํ–ˆ์„ ๋•Œ, k๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด array๊ฐ€ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด

array์˜ 2๋ฒˆ์งธ๋ถ€ํ„ฐ 5๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฅด๋ฉด [5, 2, 6, 3]์ž…๋‹ˆ๋‹ค.

1์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•˜๋ฉด [2, 3, 5, 6]์ž…๋‹ˆ๋‹ค.

2์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์˜ 3๋ฒˆ์งธ ์ˆซ์ž๋Š” 5์ž…๋‹ˆ๋‹ค.

๋ฐฐ์—ด array, [i, j, k]๋ฅผ ์›์†Œ๋กœ ๊ฐ€์ง„ 2์ฐจ์› ๋ฐฐ์—ด commands๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, commands์˜ ๋ชจ๋“  ์›์†Œ์— ๋Œ€ํ•ด ์•ž์„œ ์„ค๋ช…ํ•œ ์—ฐ์‚ฐ์„ ์ ์šฉํ–ˆ์„ ๋•Œ ๋‚˜์˜จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ

  • array์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • array์˜ ๊ฐ ์›์†Œ๋Š” 1 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • commands์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 50 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • commands์˜ ๊ฐ ์›์†Œ๋Š” ๊ธธ์ด๊ฐ€ 3์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

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

๋ฌธ์ œ์— ๋Œ€ํ•œ ๋‚˜์˜ ํ’€์ด

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for(int i = 0; i < commands.length; i++){
            int[] tempArr = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
            Arrays.sort(tempArr);
            answer[i] = tempArr[commands[i][2] - 1];
        }
        return answer;
    }
}

ํ’€์ด ๋ฆฌ๋ทฐ

solution ๋ฉ”์„œ๋“œ๋Š” ์ •์ˆ˜ ๋ฐฐ์—ด array์™€ 2์ฐจ์› ์ •์ˆ˜ ๋ฐฐ์—ด commands๋ฅผ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค.

๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  ์ •์ˆ˜ ๋ฐฐ์—ด answer๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. commands ๋ฐฐ์—ด์˜ ํฌ๊ธฐ์™€ ๋™์ผํ•œ ํฌ๊ธฐ๋กœ ์„ค์ •๋ฉ๋‹ˆ๋‹ค.

commands ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ๋ช…๋ น์–ด์— ๋Œ€ํ•ด ์ฒ˜๋ฆฌ๋ฅผ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

๊ฐ ๋ช…๋ น์–ด๋Š” ๋ฐฐ์—ด์„ ํŠน์ • ๊ตฌ๊ฐ„์œผ๋กœ ์ž๋ฅด๊ณ , ๊ทธ ๊ตฌ๊ฐ„์„ ์ •๋ ฌํ•œ ํ›„์— ํŠน์ • ์œ„์น˜์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

Arrays.copyOfRange() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ํ•ด๋‹นํ•˜๋Š” ๊ตฌ๊ฐ„์„ ๋ณต์‚ฌํ•˜์—ฌ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

๋ณต์‚ฌํ•œ ๋ฐฐ์—ด์„ Arrays.sort() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.

์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ commands[i][2] - 1 ์œ„์น˜์— ์žˆ๋Š” ๊ฐ’์„ answer[i]์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ์ฃผ์˜ํ•  ์ ์€ ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ ๋ช…๋ น์–ด์˜ ์œ„์น˜ ๊ฐ’์—์„œ 1์„ ๋นผ์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋ชจ๋“  ๋ช…๋ น์–ด์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ๋๋‚˜๋ฉด answer ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์ด ์ฝ”๋“œ๋Š” ๊ฐ ๋ช…๋ น์–ด์— ๋”ฐ๋ผ ๋ฐฐ์—ด์„ ์ž˜๋ผ๋‚ด๊ณ  ์ •๋ ฌํ•œ ํ›„์— ํŠน์ • ์œ„์น˜์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ฉ๋‹ˆ๋‹ค.