프로그래머스 k번째 수 자바

2023. 5. 13. 16:52코딩테스트/프로그래머스

https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

이 문제는 주어진 배열을 주어진 조건에 맞게 자른 후 정렬하고 k번째 수들을 구한 수를 배열에 저장을 해달라는 간단한 문제입니다.

 

일단 처음 풀 때는 객체지향은 생각하지 않고 풀어보겠습니다.

 

import java.util.Arrays;

public class Solution42748 {

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


        // 배열 자르기
        for (int i = 0; i < commands.length; i++) {
            int size = commands[i][1] - commands[i][0] + 1;

            int[] arr = new int[size];

            int index = commands[i][0] - 1;

            for (int j = 0; j < size; j++) {
                arr[j] = array[index];
                index++;
            }

            // 배열 정렬
            Arrays.sort(arr);

            // 인덱스에 맞는 값 구하기

            answer[i] = arr[commands[i][2] - 1];
        }

        return answer;
    }

    public static void main(String[] args) {
        int[] array = {1, 5, 2, 6, 3, 7, 4};
        int[][] command = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};

        Solution42748 solution42748 = new Solution42748();
        int[] result = solution42748.solution(array, command);
        System.out.println(Arrays.toString(result));
    }
}

 

두 번째는 메소드로 기능을 최대한 분리하는 방식으로 풀어보았다.

 

import java.util.Arrays;

public class Solution42748 {

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

        for (int i = 0; i < answer.length; i++) {
            int[] arr = cutArray(array, commands, i);
            findIndex(answer, arr, commands[i][2], i);
        }

        return answer;
    }
    
    // 배열 자르기
    private int[] cutArray(int[] array, int[][] commands, int i) {

        int size = commands[i][1] - commands[i][0] + 1;

        int[] arr = new int[size];

        int index = commands[i][0] - 1;

        for (int j = 0; j < size; j++) {
            arr[j] = array[index];
            index++;
        }

        return arr;
    }

    // k번째 있는 수 구하기
    private void findIndex(int[] answer, int[] arr, int idx, int i) {
        // 배열 정렬
        Arrays.sort(arr);

        answer[i] = arr[idx - 1];
    }

    public static void main(String[] args) {
        int[] array = {1, 5, 2, 6, 3, 7, 4};
        int[][] command = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};

        Solution42748 solution42748 = new Solution42748();
        int[] result = solution42748.solution(array, command);
        System.out.println(Arrays.toString(result));
    }
}