15. K번째수
https://programmers.co.kr/learn/courses/30/lessons/42748
파이썬
뭐라 뭐라 복잡하게 적어두었지만 차근차근 작성하면 다음과 같습니다.
def solution(array, commands):
answer = []
for i, j, k in commands:
a = array[i - 1:j]
a.sort()
answer.append(a[k - 1])
return answer
for와 리스트가 보인다면 리스트 컴프리헨션을 떠올려 보면 좋습니다.
sort()와 sorted()의 차이도 설명드렸죠?
https://inma.tistory.com/137
def solution(array, commands):
return [sorted(array[i - 1:j])[k - 1] for i, j, k in commands]
자바스크립트
함수형으로 풀어봅니다.
function solution(array, commands) {
var answer = [];
commands.forEach( command => {
answer.push(
array
.slice(command[0]-1,command[1])
.sort(function(a, b){return a - b})[command[2]-1])
});
return answer;
}
answer 배열을 생성하지 않고 map을 이용해서 바로 리턴하면 코드를 더 줄일 수 있습니다.
https://www.zerocho.com/category/JavaScript/post/5acafb05f24445001b8d796d
function solution(array, commands) {
return commands.map( command => {
return array
.slice(command[0]-1,command[1])
.sort(function(a, b){return a - b})[command[2]-1]
});
}
function solution(array, commands) {
return commands.map( command => {
return array
.slice(command[0]-1,command[1])
.sort((a, b) => a - b)[command[2]-1]
});
}
자바
요즘엔 주로 파이썬을 쓰는데, 오래간만에 자바를 보니 눈물이 앞을 가립니다. ㅠ,.ㅠ
코드가 복잡합니다. 취미 코딩엔 파이썬이 좋은 것 같습니다.
어레이 클래스의 API는 다음 링크를 참고하십시오.
https://palpit.tistory.com/902
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] ret = new int[commands.length];
for (short i = 0; i < commands.length; i++) {
int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
ret[i] = temp[commands[i][2]-1];
}
return ret;
}
}
고
고의 슬라이스(배열)가 참조형으로 작동함을 알아야 풀 수 있습니다.
슬라이스는 실제 배열을 가리키는 포인트 정보만을 가집니다.
실제 데이터를 복제하려면 명시적으로 copy명령을 써야 합니다.
copy를 쓰지 않고 슬라이스를 바인딩한 뒤 sort를 하면 원본 슬라이스의 순서가 바뀝니다.
import "sort"
func solution(array []int, commands [][]int) (rtn []int) {
for _, v := range commands {
newSlide := make([]int, v[1]-v[0]+1)
copy(newSlide, array[v[0]-1:v[1]])
sort.Ints(newSlide)
rtn = append(rtn, newSlide[v[2]-1])
}
return
}
append를 이용해 초기화와 카피를 동시에 해주는 방법도 있습니다.
생략 부호(...)는 슬라이스의 모든 요소들의 '집합'을 나타냅니다.
newSlide := []int{array[v[0]-1:v[1]]...} 은 안됩니다. 요소들을 집어넣어야 하는데 집합을 넣었죠?
import "sort"
func solution(array []int, commands [][]int) (rtn []int) {
for _, v := range commands {
newSlide := append([]int{}, array[v[0]-1:v[1]]...)
sort.Ints(newSlide)
rtn = append(rtn, newSlide[v[2]-1])
}
return
}
코틀린
함수형으로 풀어보았습니다.
class Solution {
fun solution(array: IntArray, commands: Array<IntArray>): IntArray {
return commands
.map { it -> // it -> 생략가능
array
.slice((it[0] - 1) until it[1])
.sorted()[it[2] - 1]
}.toIntArray()
}
}
코뽐용으로는 이렇게...
class Solution {
fun solution(array: IntArray, commands: Array<IntArray>): IntArray {
return commands.map { array.slice((it[0] - 1) until it[1]).sorted()[it[2] - 1] }.toIntArray()
}
}
C#
배열의 슬라이스는 C# 8.0 부터 지원하는데... (프로그래머스의 C#버전은 그 보다 낮아서...)
크기가 같은 2차원배열과 재그배열의 차이를 알고 있어야 쉽게 풀 수 있습니다.
public class Solution
{
public int[] solution(int[] array, int[,] commands)
{
int[] answer = new int[commands.GetLength(0)];
for (int i = 0; i < commands.GetLength(0); i++)
{
int[] temp = array[(commands[i, 0] - 1)..commands[i, 1]];
Array.Sort(temp);
answer[i] = temp[commands[i, 2] - 1];
}
return answer;
}
}
List를 이용해 봅니다.
using System.Collections.Generic;
public class Solution
{
public int[] solution(int[] array, int[,] commands)
{
int[] answer = new int[commands.GetLength(0)];
for (int i = 0; i < commands.GetLength(0); i++)
{
List<int> temp = new List<int>(array);
temp = temp.GetRange(commands[i, 0] - 1, commands[i, 1] - commands[i, 0]+1);
temp.Sort();
answer[i] = temp[commands[i, 2] - 1];
}
return answer;
}
}
ArraySegment
using System;
public class Solution
{
public int[] solution(int[] array, int[,] commands)
{
int[] answer = new int[commands.GetLength(0)];
for (int i = 0; i < commands.GetLength(0); i++)
{
int[] temp = new ArraySegment<int>(array, commands[i, 0] - 1, commands[i, 1] - commands[i, 0] + 1).ToArray();
Array.Sort(temp);
answer[i] = temp[commands[i, 2] - 1];
}
return answer;
}
}