题目:
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.
题意:
这个题目算是经典之一了。输入一个整数数组,目标是将其排序为拼接值最大的字符串。类似的题目程设遇到过,当时有大数的坑,需要手写快排;WAP面试手写代码同样的题目,当时隔了好几年没写代码;这次的版本是手写冒泡,效率很一般,哈哈~
代码:
class Solution {
public:
string largestNumber(vector<int>& nums) {
for(int i = 0; i<nums.size() ; i++)
{
for(int j = i+1; j<nums.size(); j++)
{
string num1 = to_string(nums[i]);
string num2 = to_string(nums[j]);
if(num1 + num2 < num2 + num1)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
}
string res = "";
if(nums[0] == 0)
res = "0";
else
{
for(int i = 0; i<nums.size(); i++)
{
res += to_string(nums[i]);
}
}
return res;
}
};
可以考虑剪枝,当然改写快排更快。