题目描述
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
解题思路
贪心思想。两两比较选取最大的一个,我是采取的冒泡排序来解这一道题,抛砖引玉吧算是。
代码
class Solution:
def largestNumber(self, nums: List[int]) -> str:
ans = ""
n = len(nums)
for i in range(n):
for j in range(0, n - i - 1):
s1 = str(nums[j]) + str(nums[j + 1])
s2 = str(nums[j + 1]) + str(nums[j])
if s1 > s2:
nums[j + 1], nums[j] = nums[j], nums[j + 1]
for i in range(n - 1, -1, -1):
ans += str(nums[i])
if ans[0] == '0':
return '0'
return ans