K번째수

HH·2022년 9월 25일
0

Algorithm

목록 보기
1/5

문제

문제 설명

배열 array의 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입니다.

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

제한사항

  • array의 길이는 1 이상 100 이하입니다.
  • array의 각 원소는 1 이상 100 이하입니다.
  • commands의 길이는 1 이상 50 이하입니다.
  • commands의 각 원소는 길이가 3입니다.

입출력 예

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

입출력 예 설명

[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.


풀이

내 풀이

  1. i 번째부터 j 번째까지 값을 가진 리스트를 만든다. 인덱스로는 i - 1 부터 j - 1 까지.
    1. 리스트를 정렬.
  2. 2에서 나온 배열 중 k 번째 (인덱스로 k - 1) 값을 정답 리스트에 넣는다.
  3. 정답 리스트를 배열로 바꿈
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Solution {
	public int[] solution(int[] array, int[][] commands) {
		List<Integer> answer = new ArrayList<>();
		for (int[] command : commands) {
			List<Integer> subList = new ArrayList<>();
			for (int i = command[0] - 1; i < command[1]; i++) {
				subList.add(array[i]);
			}
			subList.sort(Comparator.comparingInt(a -> a));
			answer.add(subList.get(command[2] - 1));
		}

		return answer.stream().mapToInt(i -> i).toArray();
	}
}

다른 사람 풀이

프로그래머스에서 참고용으로 다른 사람 풀이를 가져왔다.
주석은 공부용으로 내가 적은 것.

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++){
        //array의 commands[i][0]-1 ~ commands[i][1](포함 안함) 까지 범위를 복사해서 새 배열 리턴
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            //정렬
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }

        return answer;
    }
}

위 방법을 사용하면 List를 생성 -> List에 값 추가 -> List를 배열로 변환하는 과정이 필요 없다.

Arrays.copyOfRange(원본Array, 시작, 끝) // 끝 포함 안함
Arrays.copyOf(원본Array, 끝) // 시작 값 아님. 끝 포함 안함.
Arrays.sort(array)

를 배웠다.

풀이 개선

import java.util.Arrays;

public class Solution {
	public int[] solution(int[] array, int[][] commands) {
		int[] answer = new int[commands.length];
		for (int i = 0; i < commands.length; i++) {
			int[] command = commands[i];
			int[] subArray = Arrays.copyOfRange(array, command[0] - 1, command[1]);
			Arrays.sort(subArray);
			answer[i] = subArray[command[2] - 1];
		}
		return answer;
	}
}

0개의 댓글