LintCode-最大数

本文介绍了一种将非负整数数组重新排列以形成最大整数的方法。通过自定义比较器实现优先队列,确保了O(nlogn)的时间复杂度。文章特别注意了特殊情况的处理,例如全零输入及不同长度数字间的比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最大数

描述
给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数。

注意事项
最后的结果可能很大,所以我们返回一个字符串来代替这个整数。

样例
给出 [1, 20, 23, 4, 8],返回组合最大的整数应为8423201。

挑战 
在 O(nlogn) 的时间复杂度内完成。

堆排序跟优先队列都能达到O(nlogn)
坑1:输入{0,0}要输出0
坑2:前几位相同但不同长度的数字不一定长的就排在前面,如{1,10}和{8,89},短的数字要用数字本身填充后几位
一开始写的用最后一位重复填充结果ac了,但实际上{121,121120}这样的数据用最后一位填充是错的,会输出{121120121}。
如果每位都一样返回true和false就都无所谓了。

class Solution {
public:
    /*
    * @param nums: A list of non negative integers
    * @return: A string
    */

    class cmp {
    public:
        bool operator() (const int& a, const int& b) {
            string n1 = to_string(a), n2 = to_string(b);
            for (int i = 0; i < 20; i++) {
                int b1, b2;
                /*
                if (i == n1.length()) {
                    b1 = n1.back() - 48;
                } else {
                    b1 = n1[i] - 48;
                }
                if (i == n2.length()) {
                    b2 = n2.back() - 48;
                } else {
                    b2 = n2[i] - 48;
                }
                if (b1 > b2) return false;
                if (b1 < b2) return true;
                */
                int b1, b2;
                if (n1.length() == 0)  return false;
                b1 = n1[i%n1.length()] - 48;
                b2 = n2[i%n2.length()] - 48;
                if (b1 > b2) return false;
                if (b1 < b2) return true;
            }
        }
    };
    string largestNumber(vector<int> &nums) {
        // write your code here
        std::priority_queue<int, vector<int>, cmp> p;
        string result;
        for (int& i : nums) {
            p.emplace(i);
        }
        bool zero = true;
        while (!p.empty()) {
            if (zero && p.top() == 0) {
                p.pop();
                continue;
            } else {
                zero = false;
            }
            for (auto i : to_string(p.top())) {
                result.push_back(i);
            }
            p.pop();
        }
        if (zero) result.push_back('0');
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值