剑指Offer - 面试题45. 把数组排成最小的数(字符串排序)

1. 题目

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

示例 1:
输入: [10,2]
输出: "102"

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

提示:
0 < nums.length <= 100
说明:
输出结果可能非常大,所以你需要返回一个字符串而不是整数
拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0

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

2. 解题

  • 先将数字转成字符串
  • 然后对字符串排序,a+b < b+a
class Solution {
public:
    string minNumber(vector<int>& nums) {
    	vector<string> number;
    	for(auto& n : nums)
    		number.push_back(to_string(n));
    	sort(number.begin(), number.end(),[](const string& a, const string& b)
    		{return a+b < b+a;});
    	string ans;
    	for(auto& n : number)
    		ans += n;
    	return ans;
    }
};

在这里插入图片描述

发布了660 篇原创文章 · 获赞 534 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/104451645