Hinsverson / AlgorithmTop

Apache License 2.0
0 stars 0 forks source link

剑指 Offer 45. 把数组排成最小的数 #115

Open Hinsverson opened 3 years ago

Hinsverson commented 3 years ago

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

 

示例 1:

输入: [10,2]
输出: "102"

示例 2:

输入: [3,30,34,5,9]
输出: "3033459"

 

提示:

说明:

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Hinsverson commented 3 years ago

关键点:本质是排序问题,字符串拼接AB或者BA转化为整数如果AB<BA那么说明A比B小

  1. 要考虑大数问题,使用字符串存储
class Solution {
    func minNumber(_ nums: [Int]) -> String {
        var strs = nums.map{ String($0) }
        strs.sort(by: {$0 + $1 < $1 + $0})
        return strs.joined(separator: "")
    }
}