Sword refers to offer 45. Arrange the array into the smallest number
Title description
Problem-solving ideas
This question seeks the smallest number to be spliced together, which is essentially a sorting problem . Nums string array disposed between any two numbers x and y, the predetermined sorting rule is determined as:
- If the concatenated string x + y> y + x, then x is "greater than" y;
- Conversely, if x + y <y + x, then x is "less than" y;
x "less than" y means: after sorting, x should be to the left of y in the array; "greater than" is the opposite.
Added: String class compareTo()
methods for comparing two strings of size, forstr1.compareTo(str2)
- If str1 == str2, the return value is 0;
- If str1 <str2, return a value less than 0;
- If str1> str2, a value greater than 0 is returned.
1. Arrays.sort custom sort
class Solution {
public String minNumber(int[] nums) {
//保存 nums 所有元素的 String 类型
String[] stringOfNums = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
stringOfNums[i] = String.valueOf(nums[i]);
}
Arrays.sort(stringOfNums, (x, y) -> (x + y).compareTo(y + x));
StringBuilder res = new StringBuilder();
for (String str : stringOfNums) {
res.append(str);
}
return res.toString();
}
}
2. Custom Quick Sort
class Solution {
public String minNumber(int[] nums) {
//保存 nums 所有元素的 String 类型
String[] str = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
str[i] = String.valueOf(nums[i]);
}
quickSort(str, 0, nums.length - 1);
StringBuilder res = new StringBuilder();
for (String sub : str) {
res.append(sub);
}
return res.toString();
}
//自定义快速排序
public void quickSort(String[] str, int left, int right) {
if (left >= right) return;
int start = left, end = right;
String temp = str[start];
while (start < end) {
while (start < end && (str[end] + temp).compareTo(temp + str[end]) >= 0) end--;
str[start] = str[end];
while (start < end && (str[start] + temp).compareTo(temp + str[start]) <= 0) start++;
str[end] = str[start];
}
str[start] = temp;
quickSort(str, left, start - 1);
quickSort(str, start + 1, right);
}
}