Problem : https://leetcode.com/problems/move-zeroes/
Use 2 pointers approach. The slow pointer moves only when num != 0. The fast pointer moves every time.
Time Complexity = O ( N )
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = j = 0
while j < len(nums):
if nums[j] != 0:
nums[i] = nums[j]
i += 1
j += 1
while i < len(nums):
nums[i] = 0
i += 1
Another solution similar to bubble-sort. Time Complexity = O ( N ** 2 )
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = 0
N = len(nums)
while i < N:
if nums[i] != 0:
i += 1
continue
j = i
while j + 1 < N:
nums[j], nums[j+1] = nums[j+1], nums[j]
j += 1
N -= 1
No comments:
Post a Comment