"Sword refers to offer" sorts the array into the smallest number, and "Sword refers to offer" Arrays
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993? Rp = 2 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Input a positive integer array, splice all the numbers in the array into a number, and print the smallest of all the numbers that can be concatenated. For example, if the input array is {3, 32, 321}, the minimum number that can be arranged for the three numbers is 321323.
Ideas
We know that to minimize the number to be spliced and convert it into a string, the requirement is to minimize the Lexicographic Order after splicing, so we can convert the number into a string and then sort it. The sorting requirement is naturally to satisfy the minimum splicing condition. For any two strings s1 and s2, meeting s1 + s2 <s2 + s1
class Solution{public:string PrintMinNumber(vector<int> num){string ans = "";int len = num.size();if(len==0)return ans;vector<string> nums(len);for(int i = 0; i<len; i++)nums[i] = to_string(num[i]);sort(nums.begin(),nums.end(),cmp);for(int i = 0; i<len; i++)ans+=nums[i];return ans;}static int cmp(const string &s1,const string &s2){return s1+s2<s2+s1;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source