leetcode 179. Largest Number 数组可以组成最大的数

Bertha 。 2022-05-29 01:09 245阅读 0赞

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这道题和剑指offer读书笔记:第五章,优化时间和空间效率:问题05 把数组排成最小的数 的做法一模一样

不过需要注意的是字符串数组头部多余的0要去掉,嗯嗯就这样

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. #include <iomanip>
  19. #include <cstdlib>
  20. #include <ctime>
  21. using namespace std;
  22. bool cmp(int a, int b)
  23. {
  24. string aa = to_string(a);
  25. string bb = to_string(b);
  26. return aa + bb > bb + aa;
  27. }
  28. class Solution
  29. {
  30. public:
  31. string largestNumber(vector<int>& a)
  32. {
  33. sort(a.begin(), a.end(), cmp);
  34. string res;
  35. for (int i : a)
  36. res += to_string(i);
  37. while (res.size() >= 2 && res[0] == '0')
  38. res.erase(res.begin());
  39. return res;
  40. }
  41. };

发表评论

表情:
评论列表 (有 0 条评论,245人围观)

还没有评论,来说两句吧...

相关阅读