卖萌的弱渣

I am stupid, I am hungry.

Largest Number

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

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.

Solution

  • 对于两个备选数字a和b,如果str(a) + str(b) > str(b) + str(a),则a在b之前,否则b在a之前
(Largest-Number.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    # @param {integer[]} nums
    # @return {string}
    def largestNumber(self, nums):
        if not nums:
            return ""
        s = [str(x) for x in nums]
        sorted_s = sorted(s,cmp=self.compare)
        ret = "".join(sorted_s).lstrip('0')
        if ret != "":
            return ret
        else:
            return "0"


    def compare(self,a,b):
        return [1,-1][a+b>b+a]