I am trying to solve a programming quiz on Leet Code. The question is:
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
My solution
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count = 0
for item in nums:
if item == 0:
nums.remove(item)
count = 1
for i in range(0,count):
nums.append(0)
What my solution is trying to do is that:
- It traverses the entire list.
- If any item is 0, the item is removed. The counter increments by 1.
- After traversing the list, append
counter
number of 0's to the list.
However, my solution didn't pass the following test case.
Test input:
[0,0,1]
Expected output:
[1,0,0]
My output:
[0,1,0]
Where does my script go wrong?
CodePudding user response:
You can try this in a simple way:
>>> nums = [0,1,0,3,12]
>>> output=[i for i in nums if i!=0]
>>> for cnt in range(nums.count(0)):
output.extend("0")
>>> print(output)
[1, 3, 12, '0', '0']
Same code can be convert into one liner solution as suggested by @deadshot:
[i for i in nums if i!=0] [0] * nums.count(0)
CodePudding user response:
The other answer together with the one line solution from comment are nice pythonic solutions. If you really need the same list modified in place you can do something similar with bubble-sort, swap elements until all the zeroes are at the end.
nums = [0, 1, 0, 3, 12]
done = False
while not done:
done = True
for i in range(len(nums) - 1):
if nums[i] == 0 and nums[i 1] != 0:
nums[i] = nums[i 1]
nums[i 1] = 0
done = False
print(nums)
In your solution, remove
removes only the first occurrence or a zero. To make it work you need to remove until there are no zeros remaining and then append the final number of zeroes at the end.