Advertisement
smj007

Untitled

Mar 10th, 2025
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. class Solution:
  2.     def moveZeroes(self, nums: List[int]) -> None:
  3.         """
  4.        Do not return anything, modify nums in-place instead.
  5.        """
  6.  
  7.         # slow pointer to keep tracker of the non-target elements
  8.         left = 0
  9.  
  10.         # fast pointer to find the non-
  11.         for right in range(len(nums)):
  12.             if nums[right]:
  13.                 nums[left], nums[right] = nums[right], nums[left]
  14.                 left += 1
  15.  
  16.         return nums
  17.  
  18.  
  19. # However note this does not work because you are literally re-assigning the array
  20. # because you are reassigning the array rather than modifying in-place
  21. class Solution:
  22.     def moveZeroes(self, nums: List[int]) -> None:
  23.         """
  24.        Do not return anything, modify nums in-place instead.
  25.        """
  26.         slow = 0
  27.  
  28.         for fast in range(len(nums)):
  29.             if nums[fast] != 0:
  30.                 nums[slow] = nums[fast]
  31.                 slow += 1
  32.  
  33.         nums = nums[:slow] + (len(nums) - slow)*[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement