Largest Number

题目描述

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

解题方法

对于哪个数放在前面的问题,其实对于a和b两个数

如果ab > ba,那么a就应该放在b的前面,根据这一条件写一个comparator,就可以了

Solution

class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        if not nums:
            return

        def compare(a, b):
            ab = str(a) + str(b)
            ba = str(b) + str(a)
            ab = int(ab)
            ba = int(ba)
            if ab < ba:
                return - 1
            elif ab == ba:
                return 0
            else:
                return 1

        nums = sorted(nums, cmp=compare)
        if nums[-1] == 0:
            return "0"

        result = ""
        for num in nums:
            result = str(num) + result

        return result

Reference