• Home

My Codegate

  • Home

프로그래머스 K번째수 자바 문제풀이

2023/12/08 Posted by Codegate Java No Comments
프로그래머스 K번째수 자바 문제풀이

문제 링크

int 배열 array와 2차원 int 배열 commands를 받아 설명대로 처리를 해 줘야 하는데, array를 commands 배열을 가지고 한 번씩 가공하되, 2차원 배열이기 때문에 예제에서는 총 3번을 해 줘야 한다.

먼저 commands 배열을 참고해서 [2,5,3] 이렇게 있으면 2번째부터 5번째까지 잘라줘야 하는데 자르면 나와야 할 값은 5,2,6,3 이므로 인덱스 잘 확인하고, 다음은 자른 배열을 정렬한 뒤 배열에서 3번째 인덱스를 가져와 배열에 저장한 뒤 commands 배열을 모두 돌려주고 난 뒤에 반환하면 되는 식이다.

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

문제를 풀어보자면 array 배열을 가지고 commands 배열로 잘 가공해주면 끝인데, commands 배열 길이만큼 for문을 돌리면서 array 배열을 가공해야 하는데 일단 배열을 지정된 크기만큼 잘라주려면

Arrays.copyOfRange(배열, 시작_인덱스, 끝_인덱스) 을 사용해야 하는데 commands에 적혀있는 크기만큼 배열을 잘라준 후 Arrays.sort(배열) 을 이용해서 정렬하고, 이후 commands 배열의 끝자리에 있는 번호 인덱스를 가져와야 하는데, 인덱스는 0부터 시작하기 때문에 -1을 해서 가져오는 것을 잊지 말자.

이후 따로 배열에 저장해둔 뒤 for문을 돌리면서 모두 넣어주는 과정이 끝나면, 배열을 Return 해주면 끝이다.

No Comments
0

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next