본문 바로가기

알고리즘/알고리즘

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

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

 

코딩테스트 연습 - K번째수

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

programmers.co.kr

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int start;
        int end;
        int position;
        for(int i=0; i<commands.length; i++){
        	int[] init = array;
        	int[] temp = {};
          start = (commands[i][0])-1;
            end = commands[i][1];
            position = (commands[i][2])-1;
            temp = Arrays.copyOfRange(init,start,end);
            Arrays.sort(temp);
            answer[i] = temp[position];
        }
        return answer;
    }
}
package com.company;

import java.util.Arrays;

public class programmers2 {

    public static void main(String[] args) {
     //https://programmers.co.kr/learn/courses/30/lessons/42748
        int[] array = {1, 5, 2, 6, 3, 7, 4};
        int[][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};
        int[] result = Solution.solution(array, commands);
    }
    static class Solution {
        public static int[] solution(int[] array, int[][] commands) {
            int[] answer = new int[commands.length];
            //조건 시작, 끝, 탐색 2중
            for(int i=0; i<commands.length; i++){
                int[] temp = commands[i];
                int start = temp[0]-1;
                int end = temp[1];
                int search = temp[2]-1;
                int[] parsingArray = Arrays.copyOfRange(array,start,end);//배열 자르기
                //System.out.println(Arrays.toString(parsingArray));
                Arrays.sort(parsingArray);// 정렬
                answer[i] = parsingArray[search];
            }//for i end
            //System.out.println(Arrays.toString(answer));
            return answer;
        }
    }
}