관리 메뉴

솜씨좋은장씨

[leetCode] 179. Largest Number (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 179. Largest Number (Python)

솜씨좋은장씨 2020. 10. 25. 00:03
728x90
반응형

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

Note: The result may be very large, so you need to return a string instead of an integer.

 

Example 1:

Input: nums = [10,2]
Output: "210"

Example 2:

Input: nums = [3,30,34,5,9]
Output: "9534330"

Example 3:

Input: nums = [1]
Output: "1"

Example 4:

Input: nums = [10]
Output: "10"

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 10^9

첫번째 시도 - 실패 ( Fail )

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        if len(nums) == 1:
            return str(nums[0])
        elif len(nums) == 0:
            return ""
        
        else:
            temp = []
            
            for num in nums:
                temp.append((num, int(str(num)[0])))
                
            temp = sorted(temp, key=lambda x: (-x[1], -x[0]))
            
            answer = [str(t[0]) for t in temp]
            
            return "".join(answer)

두번째 시도 - Solution

class compare(str):
    def __lt__(x, y):
        return x+y > y+x

class Solution:

    
    def largestNumber(self, nums: List[int]) -> str:
        if len(nums) == 1:
            return str(nums[0])
        elif len(nums) == 0:
            return ""
        
        else:
            str_nums = [str(num) for num in nums]
            
            answer = sorted(str_nums, key=compare)
            
            if list(set(answer)) == ['0']:
                answer = ['0']
            
            return "".join(answer)

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments