LeetCode | 179. Largest Number

 

题目:

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

Note: The result may be very large, so you need to return a string instead of an integer.

 

题意:

这个题目算是经典之一了。输入一个整数数组,目标是将其排序为拼接值最大的字符串。类似的题目程设遇到过,当时有大数的坑,需要手写快排;WAP面试手写代码同样的题目,当时隔了好几年没写代码;这次的版本是手写冒泡,效率很一般,哈哈~

 

代码:

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        for(int i = 0; i<nums.size() ; i++)
        {
            for(int j = i+1; j<nums.size(); j++)
            {
                string num1 = to_string(nums[i]);
                string num2 = to_string(nums[j]);
                if(num1 + num2 < num2 + num1)
                {
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                }
            }
        }
        string res = "";
        if(nums[0] == 0)
            res = "0";
        else
        {
            for(int i = 0; i<nums.size(); i++)
            {
                res += to_string(nums[i]);
            }
        }
        return res;
    }
};

可以考虑剪枝,当然改写快排更快。

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值