[Leetcode] 179. Largest Number 解题报告

xiaoxiao2021-02-28  81

题目:

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

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

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

思路:

这道题目的思路不难,主要有三个步骤:1)重写一个特殊的比较函数,使得首位越大的数字排的越靠前;2)利用步骤1)提供的比较函数进行排序;3)将排好序的数字依次转换为字符串,并且连接起来。这里需要注意一个特殊情况,就是所有数字都是0的情况,此时不能返回“00000”等样子,而要返回“0”。我原来写的比较函数有好几十行,但时候后来发现网上有同学用C++的stl提供的to_string方法,巧妙地实现了需要的功能,代码量立即下降到十行之内。

代码:

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

转载请注明原文地址: https://www.6miu.com/read-83609.html

最新回复(0)