LeetCode--Python解析【Largest Number】(179)

题目:

方法:

class Solution:
    
    def cmp(self,x,y):
        return (x > y) - (x < y)
    
    def comper(self,x,nums):
        temp = 0
        for n in nums:
            n = str(n)
            temp += self.cmp(int(x+n),int(n+x))
            #print(self.cmp(int(x),n))
        return temp
    
    
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        temp_list = [str(x) for x in nums]
        temp_list.sort(key=lambda x:self.comper(x,nums),reverse=True)
        return "".join(temp_list).lstrip("0") or "0"
        

cmp方法比较x与y的大小,x>y返回1,x<y返回-1,x=y返回0.

comper方法将传入的x依次与nums中的元素比较x在前组合,与nums元素在前组合的大小

并且累加cmp返回的值

最后返回主函数,将nums按照带入comper,得到的值进行倒排

返回得到的结果

猜你喜欢

转载自blog.csdn.net/ZJRN1027/article/details/81219307