0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.
예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.
0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.
numbers의 길이는 1 이상 100,000 이하입니다.
numbers의 원소는 0 이상 1,000 이하입니다.
정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.
| numbers | return |
|---|---|
| [6, 10, 2] | "6210" |
| [3, 30, 34, 5, 9] | "9534330" |
제일 먼저 드는 생각: 그냥 다 문자열로 바꾸고 sort 한 다음에 합치면 안되나?
-> 안 될 거라고 생각하긴 했지만 안됨
import java.util.Arrays;
class Solution {
public String solution(int[] numbers) {
String[] temp = new String[numbers.length];
String answer = "";
for (int i=0; i<numbers.length; i++){
temp[i] = "" + numbers[i];
}
Arrays.sort(temp);
for (int i=0; i<temp.length; i++){
answer += temp[temp.length-i-1];
}
return answer;
}
}
![]() | ![]() |
|---|
import java.util.*;
class Solution {
public String solution(int[] numbers) {
String[] temp = new String[numbers.length];
String answer = "";
String tmp;
// 배열을 int -> string으로 변경
for (int i=0; i<numbers.length; i++){
temp[i] = "" + numbers[i];
}
Arrays.sort(temp);
for (int i=0; i<temp.length-1; i++){
if (temp[i].charAt(0) == temp[i+1].charAt(0)){
if (temp[i].length() == temp[i+1].length() && Integer.valueOf(temp[i]).intValue() > Integer.valueOf(temp[i+1]).intValue()){
tmp = temp[i];
temp[i] = temp[i+1];
temp[i+1] = tmp;
}
else if (temp[i].length() )
}
}
return answer;
}
}
뭔가 해보려고 했던 흔적...
(1) 일단 문자열 순으로 정렬하고,
(2) 맨 앞 글자가 같을 때
(3) 문자열의 길이가 같고 + 뒤에 있는 게 앞에 있는 것보다 작으면 자리 바꾸기 (뒤에서부터 합치려고 오름차순 정렬하는 중)
(4) 길이가 다르면...?
![]() | ![]() |
|---|
import java.util.*;
class Solution {
public String solution(int[] numbers) {
String[] temp = new String[numbers.length];
String answer = "";
String tmp;
// 배열을 int -> string으로 변경
for (int i=0; i<numbers.length; i++){
temp[i] = "" + numbers[i];
}
Arrays.sort(temp, (a, b) -> (b + a).compareTo(a + b));
if (temp[0].equals("0")) return "0";
for (int i=0; i<temp.length; i++){
answer += temp[i];
}
return answer;
}
}
통과하긴 함
람다식은 멋진 거구나