공부용

K번째 수 본문

알고리즘

K번째 수

고딕짱! 2021. 3. 24. 23:43

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

  1. array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
  2. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
  3. 2에서 나온 배열의 3번째 숫자는 5입니다.

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

 

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        
        int temp, index;
		int answer[] = new int[commands.length];
		int count = 0;

		//우선 구간을 나누기 위해 숫자 개수만큼의 배열을 생성했다.
		for(int k=0; k<commands.length; k++) {
			int tempArray[] = new int[100];
			count = 0;
			
            //구간에 맞는 배열의 수를 넣어줬다.
			for(int i=commands[k][0]-1; i<commands[k][1]; i++) {
				tempArray[count++] = array[i];
			}
			
            //정렬
			for(int i=0; i<count; i++) {
				index = i;
				for(int j=i; j<count; j++) {
					if(tempArray[index] > tempArray[j]) {
						index = j;
					}
				}
				temp = tempArray[i];
				tempArray[i] = tempArray[index];
				tempArray[index] = temp;
			}
			
            //답
			answer[k] = tempArray[commands[k][2]-1];
		}
        
        return answer;
    }
}

 

***수정사항

for(int k=0; k<commands.length; k++) {
	int tempArray[] = new int[100];
	count = 0;
			
	for(int i=commands[k][0]-1; i<commands[k][1]; i++) {
		tempArray[count++] = array[i];
	}
}

이 라인(배열)

 

int tempArray[] = Arrays.copyOfRange(array, command[k][0]-1, command[k][1]);

이렇게 줄일 수 있다. (Arrays.copyOfRange)

 

for(int i=0; i<count; i++) {
	index = i;
	for(int j=i; j<count; j++) {
		if(tempArray[index] > tempArray[j]) {
			index = j;
		}
	}
	temp = tempArray[i];
	tempArray[i] = tempArray[index];
	tempArray[index] = temp;
}

이 라인(정렬)

Arrays.sort(tempArray);

이렇게 줄일 수 있다.

 

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 tempArray[] = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
                //정렬
                Arrays.sort(tempArray);

                answer[i] = tempArray[commands[i][2]-1];

            }

            return answer;
        
   	}
}

 

 

 

'알고리즘' 카테고리의 다른 글

크래인 인형뽑기 게임  (0) 2021.03.26
같은 숫자는 싫어  (0) 2021.03.25
모의고사  (0) 2021.03.25
전화번호 목록  (0) 2021.03.25
완주하지 못한 선수  (0) 2021.03.25
Comments