Brush title Note: The minimum number arranged in an array (C ++ && python)

Brush title wins the offer:

 

Subject description:

Enter a positive integer array, the array of all the numbers arranged in a number spliced ​​together, the splice can print out all numbers smallest one. 3,32,321 input array} {e.g., print the minimum number of three numbers can be arranged to 321,323.

 

Ideas:

First number into a string and then compared, because of the need to string together for comparison. After completion of the comparison, to output sequentially.

  • If ab> ba then a than b, that
  • If ab <ba a is less than b,
  • If the a is equal to ab = ba B;

 

Knowledge added:

 

Sort () function:

Header file: #include <algorithm>

Function prototype: Sort (first_pointer, n-first_pointer +, CMP)

Parameters explanation:

  • first_poniter: first address array
  • first_pointer + n: Representative last address
  • cmp: a sort function, you can not fill call the default comparison mode, the default is ascending, descending order according to individual needs change and so on.

 

Topic Source:

C++ :

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        if(!numbers.size())
            return "";
        sort(numbers.begin(), numbers.end(), cmp);
        string res;
        for(int i=0;i<numbers.size();i++)
            res+=to_string(numbers[i]);
        return res;
    }
private:
    static bool cmp(int a,int b){
        string A=to_string(a)+to_string(b);
        string B=to_string(b)+to_string(a);
        return A < B;
    }
};

 

python:

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if(len(numbers)==0)
            return ''
        compare=lambda a,b:cmp(str(a)+str(b),str(b)+str(a))
        min_string=sort(numbers,cmp=compare)
        return ''.join(str(s) for s in min_string)

 

 

Published 22 original articles · won praise 0 · Views 567

Guess you like

Origin blog.csdn.net/SampsonTse/article/details/104050002