K번째수 (자바)

김재현·2023년 11월 16일
0

알고리즘 풀이

목록 보기
18/89
post-thumbnail

문제

정답 코드

import java.util.ArrayList;
import java.util.List;

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

        List<Integer> integerList = new ArrayList<>();

        for(int[] com : commands) {
            int a =com[0];
            int b = com[1];
            int c = com[2];

            int[] temp = new int[b-a+1];

            for(int i=a-1;i<b;i++) {
                temp[i-a+1]= array[i];
            }

            for(int i=0;i<temp.length;i++) {
                for (int j=i+1;j< temp.length;j++) {
                    if (temp[i]>temp[j]) {
                        int t = temp[j];
                        temp[j] = temp[i];
                        temp[i] = t;
                    }
                }
            }

            integerList.add(temp[c-1]);
        }

        for(int i=0;i<integerList.size();i++) {
            answer[i]=integerList.get(i);
        }

        
        
        return answer;
    }
}

이미 있는 메서드 갖다 쓰면 편하더라!
Arrays.copyOfRange
Arrays.sort(temp)

다른 사람 코드

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;
    }
}
profile
I live in Seoul, Korea, Handsome

0개의 댓글