179. Largest Number
Posted dysjtu1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了179. Largest Number相关的知识,希望对你有一定的参考价值。
Problem:
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
思路:
Solution (C++):
string largestNumber(vector<int>& nums) {
if (nums.empty()) return "";
int n = nums.size();
string ans = "";
bool flag = false;
for (int i = 0; i < n; ++i) {
if (nums[i]) { flag = true; break; }
}
shell_sort(nums);
if (flag) {
for (int i = n-1; i >= 0; --i) {
ans += to_string(nums[i]);
}
} else return "0";
return ans;
}
int max_bit(int x) {
int count = 0;
if (x == 0) return 1;
while (x) {
count++;
x /= 10;
}
return count;
}
bool is_bigger(int x, int y) {
int x_bit = max_bit(x), y_bit = max_bit(y);
if (x_bit == y_bit) return x >= y;
vector<int> v1 = get_bit(x), v2 = get_bit(y);
for (auto x : v2) v1.push_back(x);
for (auto x : v1) v2.push_back(x);
int n = v1.size();
for (int i = 0; i < n; ++i) {
if (v1[i] > v2[i]) return true;
if (v1[i] < v2[i]) return false;
}
return true;
}
vector<int> get_bit(int x) {
vector<int> v;
if (x == 0) v.push_back(x);
while (x) {
v.push_back(x%10);
x /= 10;
}
for (int i = 0; i < v.size()/2; ++i) {
swap(v[i], v[v.size()-1-i]);
}
return v;
}
void shell_sort(vector<int>& v) {
int h = 1, n = v.size();
while (h < n / 3) {
h = 3 * h + 1;
}
while (h >= 1) {
for (int i = h; i < n; ++i) {
for (int j = i; j >= h && !is_bigger(v[j], v[j-h]); j -= h) {
swap(v[j], v[j-h]);
}
}
h /= 3;
}
}
性能:
Runtime: 12 ms??Memory Usage: 7.8 MB
思路:
Solution (C++):
性能:
Runtime: ms??Memory Usage: MB
以上是关于179. Largest Number的主要内容,如果未能解决你的问题,请参考以下文章