Old Wei wins the offer to take you to learn --- Brush title series (arranged in an array 32. The smallest number)

32. The array of aligned smallest number

problem:

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.

solve:

thought:

This question, we need to make, if a + b <b + aa preceding row rule ordering, sorting the elements of the array, and can be spliced ​​together.

python code:

Here note, because the version python3 removed the cmp function, and function cmp parameters sorted, we need to use functools in cmp_to_key to replace the original cmp parameter.
It has two parameters passed cmp_to_key x, y when x> y equal to 1 to return return 0, otherwise -1

It is working mechanism in the list is the list of elements to pairwise comparison, exchange two elements when cmp return is positive

# -*- coding:utf-8 -*-
import operator
import functools
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if not numbers:
            return ""
        lmb=lambda x,y:int(str(x)+str(y))-int(str(y)+str(x))
        num=sorted(numbers,key=functools.cmp_to_key(lmb))
        return ''.join([str(i) for i in num])
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104985126