Programming/Algorithm

[Java] K번째 수 구하기 (선택정렬 활용)

아이바 2023. 11. 10. 18:21

문제 

 

 

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 함수를 작성해주세요.

제한사항
array의 길이는 1 이상 100 이하입니다.
array의 각 원소는 1 이상 100 이하입니다.
commands의 길이는 1 이상 50 이하입니다.
commands의 각 원소는 길이가 3입니다.
입출력 예
array commands return
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
입출력 예 설명
[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.

 

 

 

 

 

답 

 

import java.util.Arrays;
import java.util.Scanner;

// 선택정렬
public class Solution1 {

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

for (int i = 0; i < commands.length; i++) {
int[] temp = new int[commands[i][1] - commands[i][0] + 1];
int index = 0;
for (int j = commands[i][0] - 1; j < commands[i][1]; j++) {
temp[index++] = arr[j];
}
int[] sortedArr = sort(temp);
answer[i] = sortedArr[commands[i][2] - 1];
}
return answer;
}

public int[] sort(int[] arr) {
int[] result = arr.clone();
for (int i = 0; i < result.length - 1; i++) {
for (int j = i + 1; j < result.length; j++) {
if (result[i] > result[j]) {
int temp = result[i];
result[i] = result[j];
result[j] = temp;
}
}
}
return result;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution1 T = new Solution1();
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("2차원배열의 행을 입력");
int cn = sc.nextInt();

System.out.println("2차원배열값 입력");
int[][] commands = new int[cn][3];

for (int i = 0; i < cn; i++) {
for (int j = 0; j < 3; j++) {
commands[i][j] = sc.nextInt();
}
}
System.out.println(Arrays.toString(T.solution(arr, commands)));
}

}

 

 

풀이)

 

입력값은 arr 배열, commands 2차원 배열 두가지가 필요 

 

commands[i][0] :  array의 2번째
commands[i][1] : array의 5번째
commands[i][2] : 배열의 k 번째 수 

 

answer : commands 배열의 각 하위 배열의 조건에 따른 k번째 수들의 배열 

 

 

sort : 선택정렬 함수 

 

 

선택 정렬이란 한 번의 배열 탐색에서 가장 작은 원소의 '위치'를 찾고, 그 위치와 배열의 가장 첫 번째 원소부터 차례로 바꿔주는 방식을 사용(오름 차순으로 정렬하는 경우)하는 정렬 방식

 

 

입력 값 

 

7
1 5 2 6 3 7 4

2차원배열의 행을 입력
3

2차원배열값 입력

2 5 3
4 4 1
1 7 3

 

 

 

 

 

 

 

 

문제 출처 : https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

프로그래머스

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

programmers.co.kr

 

 

 

728x90