문제
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이 여러 개 나올 경우를 방지하기 위해 정렬된 숫자 리스트를 문자열로 변환하고, 이를 정수로 변환한 후 다시 문자열로 변환하여 반환한다.
'알고리즘' 카테고리의 다른 글
[백준(BOJ)] 2108번 통계학 - 파이썬/python (0) | 2024.01.17 |
---|---|
[리트코드(LeetCode)] 75번 Sort Colors - 파이썬/python (0) | 2024.01.17 |
[백준(BOJ)] 10814번 나이순 정렬 - 파이썬/python (0) | 2024.01.17 |
[백준(BOJ)] 2751번 수 정렬하기 2 - 파이썬/python (0) | 2024.01.17 |
[백준(BOJ)] 13905번 세부 (1) | 2024.01.13 |