"Sword refers to offer" sorts the array into the smallest number, and "Sword refers to offer" Arrays

Source: Internet
Author: User

"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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.