๋ฌธ์ ์ค๋ช
https://school.programmers.co.kr/learn/courses/30/lessons/42748
ํ๋ก๊ทธ๋๋จธ์ค
SW๊ฐ๋ฐ์๋ฅผ ์ํ ํ๊ฐ, ๊ต์ก, ์ฑ์ฉ๊น์ง Total Solution์ ์ ๊ณตํ๋ ๊ฐ๋ฐ์ ์ฑ์ฅ์ ์ํ ๋ฒ ์ด์ค์บ ํ
programmers.co.kr
๋ฐฐ์ด 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์ ๋๋ค.
์ ์ถ๋ ฅ ์
array | commands | return |
[1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
์ ์ถ๋ ฅ ์ ์ค๋ช
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅธ ํ ์ ๋ ฌํฉ๋๋ค. [2, 3, 5, 6]์ ์ธ ๋ฒ์งธ ์ซ์๋ 5์
๋๋ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 4๋ฒ์งธ๋ถํฐ 4๋ฒ์งธ๊น์ง ์๋ฅธ ํ ์ ๋ ฌํฉ๋๋ค. [6]์ ์ฒซ ๋ฒ์งธ ์ซ์๋ 6์
๋๋ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 1๋ฒ์งธ๋ถํฐ 7๋ฒ์งธ๊น์ง ์๋ฆ
๋๋ค. [1, 2, 3, 4, 5, 6, 7]์ ์ธ ๋ฒ์งธ ์ซ์๋ 3์
๋๋ค.
๋ด๊ฐ ์์ฑํ ์ฝ๋
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int m = 0; m < commands.length; m++) {
int i = commands[m][0];
int j = commands[m][1];
int k = commands[m][2];
int[] temp = new int[j-i+1];
int o = 0;
for (int n = i-1; n < j; n++) {
temp[o] = array[n];
o++;
}
Arrays.sort(temp);
answer[m] = temp[k-1];
}
return answer;
}
}
์ฝ๋ ์ค๋ช
- int[ ] answer = new int[commands.length] : commands ๋ฐฐ์ด์ ๊ธธ์ด๋งํผ ํฌ๊ธฐ๋ฅผ ๊ฐ๋ answer ๋ฐฐ์ด์ ์์ฑํ๋ค.
- for (int m = 0; m < commands.length; m++) { } : for๋ฌธ์ ์ฌ์ฉํด์ commands ๋ฐฐ์ด์ ๊ธธ์ด๋งํผ ๋ฐ๋ณตํ๋ค.
- int i = commands[m][0], int j = commands[m][1], int k = commands[m][2] : commands ๋ฐฐ์ด์ ์ฒซ ๋ฒ์งธ, ๋ ๋ฒ์งธ, ์ธ ๋ฒ์งธ ๊ฐ์ ๊ฐ๊ฐ i, j, k์ ์ ์ฅํ๋ค.
- int[ ] temp = new int[j - i + 1] : array ๋ฐฐ์ด์ i๋ฒ์งธ๋ถํฐ j๋ฒ์งธ๊น์ง์ ๋ถ๋ถ ๋ฐฐ์ด์ ์ ์ฅํ temp ๋ฐฐ์ด์ ์์ฑํ๋ค.
- int o = 0 : ์ ์ํ ๋ณ์ o๋ฅผ ์์ฑํ๊ณ 0์ผ๋ก ์ด๊ธฐํํ๋ค.
- for (int n = i; n < j; n++) { temp[o] = array[n] } : for๋ฌธ์ ์ฌ์ฉํด์ array์ i๋ฒ์งธ๋ถํฐ j๋ฒ์งธ ์์๋ฅผ temp ๋ฐฐ์ด์ ๋ณต์ฌํ๋ค.
- Arrays.sort(temp) : temp ๋ฐฐ์ด์ ์ ๋ ฌํ๋ค.
- answer[m] = temp[k-1] : ์ ๋ ฌ๋ temp ๋ฐฐ์ด์์ k๋ฒ์งธ ์๋ฅผ answer์ m๋ฒ์งธ ์ธ๋ฑ์ค์ ์ ์ฅํ๋ค.
'๐งฉ ํ๋ก๊ทธ๋๋จธ์ค > ๐ต ์๊ณ ๋ฆฌ์ฆ ํ์ด(Java)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค_๊ฐ์ฅ ๊ฐ๊น์ด ๊ฐ์ ๊ธ์ (0) | 2024.12.09 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค_๋ ๊ฐ ๋ฝ์์ ๋ํ๊ธฐ (0) | 2024.12.05 |
ํ๋ก๊ทธ๋๋จธ์ค_๋ฌธ์์ด ๋ด ๋ง์๋๋ก ์ ๋ ฌํ๊ธฐ (0) | 2024.12.03 |
ํ๋ก๊ทธ๋๋จธ์ค_์ซ์ ๋ฌธ์์ด๊ณผ ์๋จ์ด (0) | 2024.12.02 |
ํ๋ก๊ทธ๋๋จธ์ค_์ต์์ง์ฌ๊ฐํ (0) | 2024.11.30 |