算法内容 本文件实现 LeetCode 179「最大数」。目标是把一组非负整数重新排列,使拼接后的数字最大。
代码先将整数转换为字符串,再通过自定义比较函数排序。比较两个字符串时,本质上要判断 a + b 和 b + a 哪个更大,排序后顺序拼接即可。实现里手写了整数转字符串和较复杂的循环比较逻辑,并对全 0 的情况做了处理,避免返回多个前导 0。时间复杂度主要来自排序,为 O(n log n * L),L 为数字字符串比较成本。
算法实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 #include <vector> #include <iostream> #include <stack> #include <queue> #include <algorithm> #include <unordered_map> using namespace std;class Solution {public : string largestNumber (vector<int >& nums) { vector<string> snums; for (int n : nums) { snums.push_back (toString (n)); } sort (snums.begin (), snums.end (), greater); string res = "" ; int len = snums.size (); int i = 0 ; while (i < len && snums[i] == "0" ) { i++; } if (i > 0 ) i--; for (; i < len; i++) { res += snums[i]; } return res; } string toString (int a) { if (a == 0 ) return "0" ; stack<int > sa; while (a != 0 ) { sa.push (a%10 ); a/=10 ; } string res = "" ; while (!sa.empty ()) { res.push_back (sa.top () + '0' ); sa.pop (); } return res; } static bool greater (string a, string b) { int na = a.length (), nb = b.length (); int nc = na > nb ? nb : na; int i = 0 ,j = 0 ; int last_i = 0 , last_j = 0 ; while (i < na && j < nb) { while (i < na && j < nb && a[i] == b[j]) { i++; j++; } if (i == na && j == nb) { return a > b; } if (i != na && j != nb) { i = last_i; j = last_j; break ; } else { if (i == na) { i = last_i; } else { j = last_j; } last_i = i; last_j = j; } } while (i < na && j < nb) { if (a[i] > b[j]) { return true ; } else if (a[i] < b[j]) { return false ; } i++; j++; } return (na-i) > (nb-j); } void swap (int &a, int &b) { a = a+b; b = a-b; a = a-b; } };