코딩테스트/프로그래머스

🌞[JAVA] 프로그래머스 Lv1. K번째수_Arrays

sunNprize 2022. 1. 20. 12:53
  • 코드구현
      class Solution {
        public int[] solution(int[] array, int[][] commands) {
    
          // answer의 길이는 commands의 길이와 동일
          int[] answer = new int[commands.length];
    
          // commands 길이만큼 돌면서
          for (int i = 0; i < commands.length; i++) {
    
            // i는 a, j는 b, k는 c로 할당
            int a, b, c;
            a = commands[i][0];
            b = commands[i][1];
            c = commands[i][2];
    
            // copyOfRange(arr, from, to): array 배열의 a-1 인덱스부터 시작, b까지 배열 복사
            int[] temp = Arrays.copyOfRange(array, a - 1, b);
    
            // 정렬
            Arrays.sort(temp);
    
            // c번째 원소==c-1 를 answer배열에 담음
            answer[i] = temp[c - 1];
    
          } // for
    
          return answer;
        }
      }​
  • 실행결과