当前位置:网站首页>【LeetCode】179. Maximum number

【LeetCode】179. Maximum number

2022-06-23 03:38:00 LawsonAbs

1 subject

If this is the first time to do , It's still a little difficult , The key is how to think of a comparison principle ? We can think of bubble sorting , We compare the size of two numbers , If the former is larger , The exchange , Make the larger number come back . The continuous operation makes the maximum number in each round to the last place , The code is as follows :

for i in range(len(nums)):
    for j in range(len(nums)-i-1): #  Indicates that it has been arranged 
        #  Sort by size , In exchange 
        if nums[j] > nums[j+1]:
            nums[j],nums[j+1] = nums[j+1],nums[j]

But this question is to find out how to piece together to get the largest number , The principle of comparison is no longer the greater of the two numbers , But the result of the splicing of two numbers is which is bigger or smaller ?

2 thought

Sort like bubbling , However, the principle of comparison is whether a larger number can be formed .

3 Code

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        #  Put the biggest last , Then flip the array 
        for i in range(len(nums)):
            for j in range(len(nums)-i-1): #  Indicates that it has been arranged 
                #  Sort by size , In exchange 
                if int(str(nums[j]) + str(nums[j+1])) > int(str(nums[j+1]) + str(nums[j])):
                    nums[j],nums[j+1] = nums[j+1],nums[j]
        nums = list(reversed(nums))
        res = ""
        for i in nums:
            res+=str(i)
        #  Need to remove leading 0
        res = res.lstrip("0")
        if res == "":
            return "0"
        return res
原网站

版权声明
本文为[LawsonAbs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206222218012889.html