LeetCode 179. Largest Number

来源:互联网 发布:行行 知乎 编辑:程序博客网 时间:2024/05/19 20:46

Problem Statement

(Source) 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.

Tags: Sort.

Solution

class Solution:    # @param {integer[]} nums    # @return {string}    def largestNumber(self, nums):        def my_cmp(x, y):            if str(x) + str(y) < str(y) + str(x):                return 1            elif str(x) + str(y) == str(y) + str(x):                return 0            else:                return -1        nums.sort(cmp=my_cmp)        res = ''.join(map(str, nums)).lstrip('0')        return res if res else '0'

Complexity Analysis:

  • Time Complexity: O(nlogn)
  • Space Complexity: O(1)
0 0
原创粉丝点击