문제 설명
정수 배열 A에는 0 ~ 9 까지의 숫자가 랜덤하게 들어있습니다.
해당 배열에서 숫자를 2개 뽑아 조합해서 만들 수 있는 두 자리 정수 중, K번째로 큰 숫자를 출력하는 프로그램을 구현하세요.
입력 형식
· A : 한 자리 정수가 포함된 정수 배열
출력 형식
· 만들 수 있는 숫자 중 K번째로 큰 숫자를 정수로 환
제약 사항
· 2 <= A.length <= 9
· 0 <= A[i] <= 9
입출력 예시
· 입력
· A = {1, 2, 3, 4, 5}
· 출력 : 54
· 설명 : A에서 두 숫자를 뽑아 만들 수 있는 가장 큰 수는 54이다.
작성 코드
import java.util.*;
class Solution242 {
public int solution(int[] A, int K) {
int[] combinations = new int[90]; // 0~9까지 숫자를 2개 뽑아 만들 수 있는 모든 조합은 90개입니다.
int index = 0;
// A 배열에서 숫자 2개를 뽑아 모든 조합을 구합니다.
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
int num = A[i] * 10 + A[j];
if (num % 11 != 0) { // 중복된 11, 22 값을 제외합니다.
combinations[index++] = num;
}
}
}
// 오름차순으로 정렬합니다.
Arrays.sort(combinations);
// K번째로 큰 숫자를 반환합니다.
return combinations[combinations.length - K];
}
public static void main(String[] args) {
Solution242 st = new Solution242();
int[] A = {1, 2, 3, 4, 5};
int K = 1;
System.out.println(st.solution(A, K));
}
}
정답 코드
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public int solution(int[] A, int K) {
List<Integer> aList = new ArrayList<>(
Arrays.stream(A)
.boxed()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList()));
int div = K / aList.size();
String first = String.valueOf(aList.remove(div));
int mod = ((K-1) % aList.size());
String second = String.valueOf(aList.remove(mod));
return Integer.parseInt(first.concat(second));
}
public static void main(String[] args) {
Solution st = new Solution();
int[] A = {1, 2, 3, 4, 5};
int K = 1;
System.out.println(st.solution(A, K));
}
}
'연습 코딩테스트' 카테고리의 다른 글
연습문제 2-4(4) 조건을 만족하는 a, b의 쌍의 개수 (0) | 2023.04.08 |
---|---|
연습문제 2-4(3) 문자열 회전에 의한 결과 판단 (0) | 2023.04.08 |
연습문제 2-4(1) K가 자릿수로 등장한 횟수 (0) | 2023.04.08 |
연습문제 2-3(5) 마지막에 남는 사람의 번호 구하기 (0) | 2023.04.06 |
연습문제 2-3(4) 뒤집어야 하는 비트의 개수 (0) | 2023.04.06 |