LeetCode算法题179:最大数解析

给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

示例 1:

输入: [10,2]
输出: 210

示例 2:

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

说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。

这个题需要自定义一个排序方法,因为以字符串的形式组合两个数,前后不同组合的数不同,哪个大就用哪个顺序,然后这样对数组排序,最后组合即可,要注意的是结果可能是在前面有0,所以需要特殊处理一下。

C++源代码:

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        string res;
        sort(nums.begin(), nums.end(), cmp);
        for (int i = 0; i < nums.size(); ++i) {
            res += to_string(nums[i]);
        }
        return res[0] == '0' ? "0" : res;
    }
    static bool cmp(int a, int b) {
           return to_string(a) + to_string(b) > to_string(b) + to_string(a); 
    }
};

python3源代码:

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        n = len(nums)
        for i in range(n):
            for j in range(n-i-1):
                temp_1 = str(nums[j])
                temp_2 = str(nums[j+1])
                if(int(temp_1+temp_2)<int(temp_2+temp_1)):
                    nums[j] = int(temp_2)
                    nums[j+1] = int(temp_1)
        res = ""
        for i in nums:
            res += str(i)
        return str(int(res))
    

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/88115125
今日推荐