[ProblemSolving JAVA]プログラマー-レベルk[レベル1]


問題の説明は省略します。リンクをクリックしてください。


提问链接


I/O例


私の答え


再認識の事実!
配列を出力する場合、System.out.println(answer)はアドレス値を出力します.
Pythonに慣れて、いつもこのような間違いを犯します.Arrays.toString()を使用して、配列入力をパラメータで受信し、文字列として返します.

コード#コード#


マイコード

import java.util.*;
public class k번째수 {

    public static void main(String [] args){
        k번째수 s = new k번째수();
        int [] a = {1, 5, 2, 6, 3, 7, 4} ;
        int [][] b = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}} ;
        int [] answer = s.solution(a,b);
        System.out.println(Arrays.toString(answer)); // 파라미터로 배열 입력 받아 문자열 형태로 리턴



    }
    // 프로그래머스 코드 
    public int[] solution(int[] array, int[][] commands){
        int [] answer = new int[commands.length];
        int idx = 0;
        for (int i=0; i<commands.length; i++){
            int start = commands[i][0];
            int end = commands[i][1];
            int k = commands[i][2];

            int a = 0;
            int [] tmp = new int[end- start +1];
            for(int j = start-1; j<end ; j++){
                tmp[a++] = array[j];
            }
            Arrays.sort(tmp);
            answer[idx++] = tmp[k-1];
            
        }
        return answer;
    }
}
  • その他の分コード
  • import java.util.Arrays;
    class Solution {
        public int[] solution(int[] array, int[][] commands) {
            int[] answer = new int[commands.length];
    
            for(int i=0; i<commands.length; i++){
                int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
                Arrays.sort(temp);
                answer[i] = temp[commands[i][2]-1];
            }
    
            return answer;
        }
    }