def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ k=0 #step1:move all none zero numbers to the front for num in nums: if num!=0: nums[k]=num k+=1 nums[k:]=*(len(nums)-k) #step2: set the rest of the list to be zero
Doesn't enumerate(nums) functionally create a copy of nums for the enumerator, violating the requirement that the solution be in-place?
enumerate doesn't create a copy. Demo:
>>> a = [4, 5] >>> e = enumerate(a) >>> a[:] = [6, 7, 8] >>> list(e) [(0, 6), (1, 7), (2, 8)]
Well no that isn't an exact copy, but what I meant is that enumerate creates a separate object that occupies additional memory. So using enumerate would not be in-place to my understanding.
And @Hendrik_van_Oost, I believe your updated code looks good to me.
k=0 creates a new object that occupies additional memory. And
*(len(nums)-k) might even create a new list as big as the input.
enumerate is fully ok (except that it was misused here because the index wasn't used (I'm looking at google's cache to see the original)).
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.