23
loading...
This website collects cookies to deliver better user experience
nums
, move all 0's
to the end of it while maintaining the relative order of the non-zero elements.nums=[8,0,3,5,0,4]
nums=[8,3,5,4,0,0]
in place
constraint would be to make a copy of the array and insert non-zero elements by:nums=[8,0,3,5,0,4]
def move_zeroes():
zeroes=[]
non_zeroes=[]
for i in nums:
if i ==0:
zeroes.append(i)
for i in nums:
if i !=0:
non_zeroes.append(i)
print(non_zeroes + zeroes)
def move_zeroes():
pri nt([i for i in nums if i !=0]+[i for i in nums if i ==0])
i
and j
. i
will be our slowest pointer while j
the fastest. def move_zeroes():
length=len(nums)
# print(length)
i=j=0
def move_zeroes():
length=len(nums)
# print(length)
i=j=0
while j < length:
if nums[j]==0:
j +=1
else:
nums[i],nums[j]=nums[j],nums[i]
j +=1
i +=1
print(nums)
j
our fastest pointer. As long as it is within the length of our array:j
is not zero then we swap j
and i
then move each of them forwards.