传送门
nowcoder
leetcode
题目描述
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如:输入数组 { 3,32,321 } ,则打印出这三个数字能排成的最小数字为 321323。
C++ 代码 - nowcoder
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
|
class Solution { public: string PrintMinNumber(vector<int>& nums) { vector<string> numStr; for (auto num : nums) { numStr.push_back(to_string(num)); } sort(numStr.begin(), numStr.end(), [](const string & a, const string & b) { return a + b < b + a; });
string res; for (auto t : numStr) { res += t; } return res; } };
class Solution { public: string PrintMinNumber(vector<int>& nums) { string res = ""; sort(nums.begin(), nums.end(), cmp); for (auto& num : nums) { res += to_string(num); } return res; }
static bool cmp(int a, int b) { string A = "", B = ""; A = to_string(a) + to_string(b); B = to_string(b) + to_string(a); return A < B; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution { public: string crackPassword(vector<int>& nums) { int n = nums.size(); vector<string> res(n); for (int i = 0; i < n; i ++) { res[i] = to_string(nums[i]); } sort(res.begin(), res.end(), [](const string& s1, const string& s2) { return (s1 + s2) < (s2 + s1); });
return accumulate(res.begin(), res.end(), string("")); } };
|