First, preface
The problem is done in Friday, start thinking a bit of problems, consider not all, resulting in submit 3 times before AC.
Second, the title 283 Move Zeroes
Given an array nums
, write a function to move all's to the 0
end of it while maintaining the relative order of the No N-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should is [1, 3, 12, 0, 0]
.
Note:
1. You must does this in-place without making a copy of the array.
2. Minimize the total number of operations.
See the first response to the topic is to take the non-0 items out into another list, and then complete the 0, but the topic clearly said without making a copy of the array, so forget it.
Three, the thinking of solving problems
Remove the 0 items corresponding to the position in the list, delete the 0 items from the back, and the corresponding relationship will be deleted by deleting a supplementary item (0).
The code is as follows, Runtime:88ms.
classsolution (object):defmovezeroes (Self, nums):""": Type Nums:list[int]: rtype:void do not return anything, modify Nums in-place instead. """Count=0 Tags=[] forNuminchNums:count+=1ifnum = =0:ifSTR (COUNT-1) not inchTags:tags.append (Count-1) forTaginchTags[::-1]: delNums[tag] Nums.append (0)
Think this is not concise, and see the next discuss in the excellent solution, also record a bit.
Put the non-0 items back in front of the list and fill 0. Runtime:80ms.
classsolution (object):defmovezeroes (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 forNuminchNums:ifnum!=0:nums[k]=Num k+=1Nums[k:]=[0]* (Len (nums)-K)#Step2:set The rest of the list to be zero
Leetcode Brush title Record [python]--283 Move zeroes