합리적 낙관주의자

Programmers [정렬] K번째수 본문

Computer Thinking 🌟/Algorithm 📝

Programmers [정렬] K번째수

sroa.chin 2020. 10. 23. 18:47

programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr


1. 내가 푼 코드

이중 for문 사용해서 주어진 범위를 list에 집어넣은 다음, Collections sort 사용해서 정렬 뒤 K번째 값 구하기 

import java.util.Collections;
import java.util.LinkedList;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int [] answer = new int [commands.length];
		
		for (int i = 0; i < commands.length; i++) {
			LinkedList<Integer> list = new LinkedList<>();
			for (int j = commands[i][0]; j <= commands[i][1]; j++) {
				list.add(array[j-1]);
			}
			
			Collections.sort(list);
			answer[i] = list.get(commands[i][2]-1);
		}
		return answer;
    }
}

 

2. 가장 많은 사람들이 푼 코드

for문 안에서 범위값을 Array에 넣어주기 위해 copyOfRange 함수 사용 


copyOfRange(int[] Original, int from, int to) - Original 배열의 인덱스 from~ to-1 범위의 새로운 배열을 반환한다.

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case 0 is placed in all elements of the copy whose index is greater than or equal to original.length - from.

The length of the returned array will be to - from.

Parameters:

original the array from which a range is to be copied (기준이 되는 배열)

from the initial index of the range to be copied, inclusive (포함)

to the final index of the range to be copied, exclusive. (This index may lie outside the array.) (미포함)

Returns: (새로운 array 반환)

a new array containing the specified range from the original array, truncated or padded with zeros to obtain the required length

Throws:

ArrayIndexOutOfBoundsException - if from < 0 or from > original.length (시작 인덱스가 original의 길이보다 클때)

IllegalArgumentException - if from > to (시작 인덱스가 끝 인덱스보다 클 때)

NullPointerException - if original is nullSince: 1.6 (배열이 null값)


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;
    }
}