CS-Notes/notes/45. 把数组排成最小的数.md
2020-11-17 00:32:18 +08:00

30 lines
1.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 45. 把数组排成最小的数
## 题目链接
[牛客网](https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
输入一个正整数数组把数组里所有数字拼接起来排成一个数打印能拼接出的所有数字中最小的一个例如输入数组 {332321}则打印出这三个数字能排成的最小数字为 321323
## 解题思路
可以看成是一个排序问题在比较两个字符串 S1 S2 的大小时应该比较的是 S1+S2 S2+S1 的大小如果 S1+S2 \< S2+S1那么应该把 S1 排在前面否则应该把 S2 排在前面
```java
public String PrintMinNumber(int[] numbers) {
if (numbers == null || numbers.length == 0)
return "";
int n = numbers.length;
String[] nums = new String[n];
for (int i = 0; i < n; i++)
nums[i] = numbers[i] + "";
Arrays.sort(nums, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
String ret = "";
for (String str : nums)
ret += str;
return ret;
}
```