오늘은 이미 깃커밋 했지만,,,
리트코드의 의리를 저버리지 않기 위해서 (?) 했다.
난이도는 Easy라서 진짜 Easy하다.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for num in nums:
if num == 0:
nums.remove(num)
nums.append(0)
in-place로 해야한다길래 파이썬의 좋은 기능이라고 할 수 있는 remove, append를 사용하였다.
코드는 보는 바와 같이 간단하다.
Time Complexity : O(n)
Success!했는데... 하위 95%란 말이잖아 엉엉
그래서 python의 append, remove기능을 사용하지 않고 (약간 C처럼) 코드를 짜보기로 결심했다.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
i와 j라는 두 인덱스가 처음에는 같이 0을 가리킨다.
숫자가 0이 아닐 때에는 계속 같이 가서 자리가 바뀌지 않는데,
0이 나타나는 순간 j의 인덱스는 i의 인덱스보다 하나 더 작게 된다.
그래서 다음에 숫자가 올 때, i와 j의 자리를 바꾸면 0이 자연스럽게 뒤에 가게 되는 것이다!
Success! 물론 겨우 5% 줄었지만 memory usage도 줄고, runtim도 엄청 줄어든게 보인다.
차근차근 코딩 연습하면서 클린 코드를 만들어나가고 싶다.
파이팅!
'Leetcode' 카테고리의 다른 글
Leetcode 557. Reverse Words in a String III (0) | 2021.10.08 |
---|---|
Leetcode 167. Two Sum II - Input array is sorted (0) | 2021.10.07 |
Leetcode 189. Rotate Array (0) | 2021.10.05 |
Leetcode 977. Squares of a Sorted Array - Two Pointers (0) | 2021.10.04 |
Leetcode 35. Search Insert Position - Binary Search (0) | 2021.10.03 |