Title: Enter a positive integer array, the array stitching together all the numbers lined up a number, print out all the numbers can be spliced in the smallest one. 3,32,321 input array} {e.g., print the minimum number of three numbers can be arranged to 321,323.
Ideas:
write a collation, the two figures are translated into strings, and then after comparing different sort order of strings, the output of the smaller one.
Finally, the sorted array in order to splice a good output.
class Solution{
public:
string PrintMinNumber(vector<int> numbers){
string ans;
if (numbers.empty()) return ans;
sort(numbers.begin(), numbers.end(), cmp);
for (int i = 0; i < numbers.size(); ++i)
{
ans += to_string(numbers[i]);
}
return ans;
}
static bool cmp(int a, int b)
{
string str1 = to_string(a);
string str2 = to_string(b);
return (str1 + str2) < (str2 + str1);
}
};
The python Solution:
wherein the lstrip () method is used or a specified character string truncated space left.
# -*- coding:utf-8 -*-
from functools import cmp_to_key
class Solution:
def cmp(self, a, b):
if a + b > b + a:
return 1
if a + b < b + a:
return -1
else:
return 0
def PrintMinNumber(self, numbers):
# write code here
if len(numbers) == 0:
return ""
numstr = list(map(str, numbers))
numstr.sort(key=cmp_to_key(self.cmp))
return"".join(number).lstrip('0')