Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion week1/2. K번째 수/Solution.java
Original file line number Diff line number Diff line change
@@ -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<Integer> answer = new ArrayList<Integer>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만들어질 배열의 길이를 알 수 있는데 List를 사용할 필요가 있을까요


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();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

List를 배열로 만들기 위해 stream api를 거치는 것 보다 toArrray() 메서드를 이용하는게 좋을것 같습니다.
내부에서 mapToInt 내에서 아무 로직도 수행하지 않는데 굳이 필요 할까요?
만약 위에서 길이가 정해진 배열을 만들었다면 List를 배열로 다시 만들 필요가 없을 것 입니다.

}

}
20 changes: 20 additions & 0 deletions week1/2. K번째 수/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function solution(array = [], commands = [[], []]) {
Copy link
Collaborator

@whdgns5059 whdgns5059 Jul 7, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

클로저의 내부 변수는 외부에서 참조가 가능해지므로 가비지 컬렉션에 의해 사라지지 않아 함수의 실행 이후 지속적으로 참조가 가능합니다. 다만 자원을 점유하게 되는데요.
이 함수에는 내부변수가 없고 실행이후 지속적으로 참조할 필요가 없는데. 클로저로 작성한 이유가 있나요?

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],
]
)
);