Leetcode - 179 最大数

本文介绍了如何使用Python的stringstream和自定义比较函数,对整数向量进行按字符串形式的大数排列。通过vector转string,利用字符串拼接规则实现快速排序,最后返回最大的数作为结果。

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

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        auto cmp = [](const int &x, const int &y) {
            long sx = 10, sy = 10;
            while (sx <= x) {
                sx *= 10;
            }
            while (sy <= y) {
                sy *= 10;
            }
            return sy * x + y > sx * y + x;//如果为真就是第一个参数在前第二个参数在后
        };
        sort(nums.begin(), nums.end(),cmp);
        string result;
        if (nums[0] == 0) {//已经按照从大到小排序了
            return "0";
        }
        for (int &x : nums) {
            result += to_string(x);
        }
        return result;
    }
};

stringstream

    // int -> string
    stringstream sstream;
    string strResult;
    int nValue = 1000;
 
    // 将int类型的值放入输入流中
    sstream << nValue;
    // 从sstream中抽取前面插入的int类型的值,赋给string类型
    sstream >> strResult;
	stringstream sstream;
    // 将多个字符串放入 sstream 中
    sstream << "first" << " " << "string,";
    sstream << " second string";
    // 可以使用 str() 方法,将 stringstream 类型转换为 string 类型;
    cout << "strResult is: " << sstream.str() << endl;
 	// 清空 sstream 之 str("") 
    sstream.str("");

    // 清空 sstream 之 clear() 方法
    sstream.clear();
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> str;
        for(auto i : nums) {
            str.push_back(to_string(i));
        }
        // 直接根据拼接结果
        auto cmp = [](string left, string right) {
            return left + right > right + left;
        };
        sort(str.begin(),str.end(), cmp);
        stringstream ss;
        for(auto c : str) {
            ss << c;
        }
        string ans = ss.str();
        if(ans[0] == '0'){
            return "0";
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值