[プログラマー]K個の数字(LEVEL 1に揃える)



質問する


配列の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です.
配列配列、[i、j、k]を要素とする2次元配列コマンドをパラメータとして与える場合は、commandsのすべての要素に前述の演算を適用した結果を配列に戻してsolution関数を作成します.

せいげんじょうけん


arrayの長さは1または100以下です.
arrayの各要素は1または100未満です.
コマンドの長さは1または50を超えません.
コマンドの各要素の長さは3です.

I/O例


array commands return
[1, 5, 2, 6, 3, 7, 4][2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

私の答え


初めて試した時に2回テストに失敗しましたsort()しか書いていないので.sort()に関するMDNドキュメントでは、正式な構文はarr.sort([compareFunction])であり、compareFunctionを入力しない場合は、各文字のUnicodeコードポイント値に基づいてソートされます.だからあなたを確定させるために.sort(function(a, b) { return a - b; })コードを修正しました.そのまま通過!
function solution(array, commands) {
  var answer = [];
  
  for(let i =0; i<commands.length; i++){
    const sortedArray = array.slice(commands[i][0]-1, commands[i][1])
    sortedArray.sort(function(a, b) {
  return a - b;
})
    answer.push(sortedArray[commands[i][2]-1])
  }

    return answer;
}

他人の解答1


非構造化割り当てによりコードに可読性を持たせる部分が印象的である.
const [sPosition, ePosition, position] = command;

function solution(array, commands) {
    return commands.map(command => {
        const [sPosition, ePosition, position] = command
        const newArray = array
            .filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
            .sort((a,b) => a - b)    

        return newArray[position - 1]
    })
}

他人の解答2


これはコードで、constに割り当てるのではなく、返信でコードを簡潔に書くように考え直させます.
次の問題は必ず実践しなければならない.
function solution(array, commands) {
    return commands.map(v => {
        return array.slice(v[0] - 1, v[1]).sort((a, b) => a - b).slice(v[2] - 1, v[2])[0];
    });
}