To prove safety Offer (32): the smallest number arranged in an array

To prove safety Offer (32): the smallest number arranged in an array

Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners

First, the primer

This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click CSDN and github link:
prove safety Offer complete analytical exercises CSDN address
github address

Second, the title

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.

1, ideas

Encounter this problem, of course, the whole arrangement can be done, but time complexity is O (n!). Here we define ourselves a rule, after a string of splicing were compared.

Sort rules are as follows:

If ab> ba then a than b, that example: a = 3 b = 32 ab = 332 ba = 323 so that a is greater than b following rules and consistent with this comparison method
if ab <ba is a is smaller than b,
if ab = ba is a equal to B;

According to the rules above, we first need to be converted into a digital string then compared, because of the need to string together for comparison. After completion of the comparison, to output sequentially.

2, programming

python

Code implementation:

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if numbers is None:
            return ""
        lens = len(numbers)
        if lens ==0 :
            return ""
        tmpNumbers = sorted(numbers,cmp=self.compare)
        return int(''.join(str(x)for x in tmpNumbers))
    def compare(self,num1,num2):
        t = str(num1)+str(num2)
        s = str(num2)+str(num1)
        if t>s:
            return 1
        elif t<s:
            return -1
        else:
            return 0

AIMI-CN AI learning exchange group [1015286623] for more information on AI

Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!

Guess you like

Origin www.cnblogs.com/aimi-cn/p/11510780.html