[프로그래머스] K번째 수 / 정렬

Urther·2021년 9월 14일
0

알고리즘

목록 보기
5/41


Problem | K번째 수

배열 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 함수를 작성해주세요.
import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer=new int[commands.length];
        /*값 읽어오기*/
        for(int i=0;i<commands.length;i++){
            ArrayList<Integer> a=new ArrayList<Integer>();
            
            int one=commands[i][0];
            int two=commands[i][1];
            int three=commands[i][2];
            
            for(int j=one;j<=two;j++)
                a.add(array[j-1]);
            /*a정렬*/
            Collections.sort(a);
            answer[i]=a.get(three-1);
        }
        return answer;
    }
}

예를들어 2차원 배열에서 a[0]번째있는 것이 [1,2,3]이라 치면 어차피 3개가 들어올 것이므로,

    int one=commands[i][0];
    int two=commands[i][1];
    int three=commands[i][2];

위와 같이 번거로운 방법을 썼다.....

왠만하면 for문을 줄이고 싶은데 이건 for문 2개 쓰는게 최선일 것 같다 ! 시간복잡도는 아마.. commands length(최대 50) * arrays 길이(최대 100) = O(N X M) 이다. 5000번정도는 1초만에 수행가능 할 것이므로 일단 이 문제에선 for문 두 개 써도 안전하다. !!

profile
이전해요 ☘️ https://mei-zy.tistory.com

0개의 댓글