๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค[Java] - K๋ฒˆ์งธ์ˆ˜(์ •๋ ฌ)

by ์ฃผ๋ฐœ2 2020. 3. 4.
๋ฐ˜์‘ํ˜•

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

์ฝ”๋“œ

import java.util.*;

class Solution {
public int[] solution(int[] array, int[][] commands) {
		int[] answer = new int[commands.length];
		for(int i=0; i<commands.length; i++) {
			// ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์˜ ํฌ๊ธฐ -> commands[i][1] ~ commands[i][0]๊นŒ์ง€ ์ž๋ฅธ ํ›„ ์ •๋ ฌํ•˜๋ฏ€๋กœ ๋‘ ๊ฐ’ ๋นผ๊ณ  +1
			int[] arr = new int[commands[i][1] - commands[i][0] + 1];
			int arrIndex = 0;
			
			// commadns์˜ [i][0]-1 ~ [i][1]๊นŒ์ง€ ์ž˜๋ผ์„œ array ๋ฐฐ์—ด์˜ ์š”์†Œ ๊ฐ’์„ arr์— ์ €์žฅํ•˜๊ธฐ.
			// ์˜ˆ์ œ๋Œ€๋กœ 2๋ฒˆ์งธ ~ 5๋ฒˆ์งธ๋ผ๋ฉด ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค์ƒ 1, 2, 3, 4 ๊ฐ’์ด ๋“ค์–ด๊ฐ€์•ผ ํ•˜๋ฏ€๋กœ -1 ํ•ด์คŒ.
			for(int j=commands[i][0]-1; j<commands[i][1]; j++) {
				arr[arrIndex++] = array[j];
			}
			
			Arrays.sort(arr);	// ๋ฐฐ์—ด ์ •๋ ฌ
			answer[i] = arr[commands[i][2] - 1];
		}
		return answer;
	}
}

ํ’€์ด

 

๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ๋Œ€๋กœ ๊ทธ๋Œ€๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

commands[][] ๋ฐฐ์—ด์˜ ๊ฐ ํ–‰๋งˆ๋‹ค ์ƒˆ๋กœ์šด ๋ฐฐ์—ด(arr)์„ ๋งŒ๋“ ๋‹ค.

์ƒˆ๋กœ์šด ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋Š” ์ฃผ์–ด์ง„ commands์˜ ์ฒซ๋ฒˆ์งธ ์—ด - 0๋ฒˆ์งธ์—ด + 1 ์„ ํ•˜๋ฉด ๋˜๋Š”๋ฐ,

2๋ฒˆ์งธ ~ 5๋ฒˆ์งธ๋Š” 5 - 2 + 1 = 4

4๋ฒˆ์งธ ~ 4๋ฒˆ์งธ๋Š” 4 - 4 + 1 = 1

1๋ฒˆ์งธ ~ 7๋ฒˆ์งธ๋Š” 7 - 1 + 1 = 7

์œ„์™€ ๊ฐ™์ด ๋˜๋ฏ€๋กœ, ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ์ •ํ•ด์ค€๋‹ค.

 

commands[i][0] ~ commands[i][1] ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด(arr)์— ๋„ฃ๊ณ , 

์ƒˆ๋กœ์šด ๋ฐฐ์—ด(arr)์„ ์ •๋ ฌํ•œ ํ›„ arr[commands[i][2]-1] ์„ answer ๋ฐฐ์—ด์— ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋Š” 0๋ถ€ํ„ฐ์ด๋ฏ€๋กœ, ํ•œ์นธ์”ฉ ๋‹น๊ฒจ์„œ -1์„ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

[1, 5, 2, 6, 3, 7, 4] ๋ฅผ 2๋ฒˆ์งธ ~ 5๋ฒˆ์งธ ์ž๋ฅธ ํ›„ ์ •๋ ฌ => [5, 2, 6, 3] => [2, 3, 5, 6]

2๋ฒˆ์งธ ~ 5๋ฒˆ์งธ ์ด์ง€๋งŒ, ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋กœ๋Š” 1, 2, 3, 4 ๊ฐ€ ๋œ๋‹ค.

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€