From 9a30986667a8ccc1a867fff77327710faa825496 Mon Sep 17 00:00:00 2001 From: wlsgud Date: Mon, 6 Jul 2020 20:33:03 +0900 Subject: [PATCH] 1-2 k-number --- .../Solution.java" | 30 ++++++++++++++++++- .../solution.js" | 20 +++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 "week1/2. K\353\262\210\354\247\270 \354\210\230/solution.js" diff --git "a/week1/2. K\353\262\210\354\247\270 \354\210\230/Solution.java" "b/week1/2. K\353\262\210\354\247\270 \354\210\230/Solution.java" index 1036e2c..028c0d4 100644 --- "a/week1/2. K\353\262\210\354\247\270 \354\210\230/Solution.java" +++ "b/week1/2. K\353\262\210\354\247\270 \354\210\230/Solution.java" @@ -1,11 +1,39 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /* 2. K번째 수 https://programmers.co.kr/learn/courses/30/lessons/42748 */ class Solution { + public static void main(String[] args) { + Solution sol = new Solution(); + + int[] arr = { 1, 5, 2, 6, 3, 7, 4 }; + int[][] commands = { { 2, 5, 3 }, { 4, 4, 1 }, { 1, 7, 3 } }; + + System.out.println(Arrays.toString(sol.solution(arr, commands))); + } + public int[] solution(int[] array, int[][] commands) { - return null; + + List answer = new ArrayList(); + + for (int[] command : commands) { + + int startIndex = command[0] - 1; + int endIndex = command[1]; + int pickIndex = command[2] - 1; + + int[] commandCopy = Arrays.copyOfRange(array, startIndex, endIndex); + Arrays.sort(commandCopy); + + answer.add(commandCopy[pickIndex]); + } + + return answer.stream().mapToInt(i -> i).toArray(); } } diff --git "a/week1/2. K\353\262\210\354\247\270 \354\210\230/solution.js" "b/week1/2. K\353\262\210\354\247\270 \354\210\230/solution.js" new file mode 100644 index 0000000..23548c7 --- /dev/null +++ "b/week1/2. K\353\262\210\354\247\270 \354\210\230/solution.js" @@ -0,0 +1,20 @@ +function solution(array = [], commands = [[], []]) { + return commands.map((command) => { + const [startIndex, endIndex, pickIndex] = command; + + return array.slice(startIndex - 1, endIndex).sort((a, b) => a - b)[ + pickIndex - 1 + ]; + }); +} + +console.log( + solution( + [1, 5, 2, 6, 3, 7, 4], + [ + [2, 5, 3], + [4, 4, 1], + [1, 7, 3], + ] + ) +);