Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- db
- adaptive remeshing
- LeetCode
- Mesh
- SQL
- 오블완
- code
- Database
- mysql
- CS
- Data_Structure
- CNN
- 컴퓨터공학
- Leet Code
- 데이터베이스
- 데이터
- 티스토리챌린지
- Python
- 자료구조
- 코딩테스트
- 개발자
- 대학생
- meshgraphnet
- 데베
- coding
- 코테
- GNN
- 컴퓨터사이언스
- DS
- sort
Archives
- Today
- Total
sy1214ei 님의 블로그
[Leet Code] 179. Largest Number 본문
[Level] Medium
[Topics] Array String Greedy Sorting
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Idea
Code (Not used Compare Function)
class Solution:
def largestNumber(self, nums: List[int]) -> str:
if len(nums) > 1:
mid = len(nums) // 2 # mid is index
L = nums[:mid]
R = nums[mid:]
self.largestNumber(L)
self.largestNumber(R)
i = j = k = 0 # i, j, k is index
while i < len(L) and j < len(R): # L and R left any index
a = L[i]; a = str(a) # '3'
b = R[j]; b = str(b) # '30'
concat_ab = a + b; concat_ab = int(concat_ab) # 330
concat_ba = b + a; concat_ba = int(concat_ba) # 303
if concat_ab > concat_ba:
nums[k] = L[i] # 3
i += 1
else :
nums[k] = R[j]
j += 1
k += 1
while i < len(L) : # L left any index
nums[k] = L[i]
i += 1
k += 1
while j < len(R) : # R left any index
nums[k] = R[j]
j += 1
k += 1
result = ''.join(str(num) for num in nums)
# "000..." 같은 경우 처리
return '0' if result[0] == '0' else result
# Time Complexity : O(NlogN)
# Space Complextiy : O(1)
Code (Used Compare Function)
class Solution:
def compare(self, n1, n2):
n1 = str(n1); n2 = str(n2)
if int(n1+n2) > int(n2+n1):
return int(n1)
else :
return int(n2)
def largestNumber(self, nums: List[int]) -> str:
if len(nums) > 1:
mid = len(nums) // 2 # mid is index
L = nums[:mid]
R = nums[mid:]
self.largestNumber(L)
self.largestNumber(R)
i = j = k = 0 # i, j, k is index
while i < len(L) and j < len(R): # L and R left any index
nums[k] = self.compare(L[i], R[j])
if nums[k] == L[i]:
i += 1
else :
j += 1
k += 1
while i < len(L) : # L left any index
nums[k] = L[i]
i += 1
k += 1
while j < len(R) : # R left any index
nums[k] = R[j]
j += 1
k += 1
result = ''.join(str(num) for num in nums)
# "000..." 같은 경우 처리
return '0' if result[0] == '0' else result
'[Coding]' 카테고리의 다른 글
| [Leet Code] 414. Third Maximum Number (1) | 2024.11.25 |
|---|---|
| [Leet Code] 350. Intersection of Two Arrays II (0) | 2024.11.25 |
| [Leet Code] 349. Intersection of Two Array (1) | 2024.11.25 |
| [Leet Code] 217. Con tains Duplicate (3) | 2024.11.25 |
| [Leet Code] 56. Merge Intervals (0) | 2024.11.24 |