알고리즘

[리트코드(LeetCode)] 179번 Largest Number - 파이썬/python

욘아리 2024. 1. 17. 21:23

https://leetcode.com/problems/largest-number/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

항목들을 조합하여 만들 수 있는 가장 큰 수를 출력하는 문제다.

예시

Example 1:

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

 

Example 2:

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

풀이

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        def compare(a, b):
            return str(a) + str(b) > str(b) + str(a)

        iters = len(nums) - 1
        for i in range(iters):
            wall = iters - i
            for j in range(wall):
                if not compare(nums[j], nums[j + 1]):
                    nums[j], nums[j + 1] = nums[j + 1], nums[j]

        return str(int(''.join(map(str, nums))))

 

- 두 개의 숫자를 문자열로 변환 후, 결합한 결과물을 비교하여 크기를 판단하는 함수를 만들어 정렬 시 사용한다.

- 버블 정렬을 사용하여 숫자 리스트를 정렬한다. 현재 위치의 숫자와 그다음 위치의 숫자를 비교하고 순서가 잘못되어 있다면 위치를 바꿔준다.

- 0이 여러 개 나올 경우를 방지하기 위해 정렬된 숫자 리스트를 문자열로 변환하고, 이를 정수로 변환한 후 다시 문자열로 변환하여 반환한다.