I want to just move the zero’s to left and don’t want to sort the list.
For example, if my list is like:
JavaScript
x
2
1
nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
2
Here’s the output which I desire after moving all the Zero’s to left:
JavaScript
1
2
1
output = [0, 0, 0, 1, 10, 20, 59, 63, 8]
2
Here’s the code I tried:
JavaScript
1
11
11
1
class Solution:
2
def moveZeroes(self, nums):
3
c = 0
4
for i in range(len(nums)):
5
if nums[i] != 0:
6
nums[i], nums[c] = nums[c], nums[i]
7
c += 1
8
return nums
9
print(Solution().moveZeroes(nums))
10
11
This code gives me output as:
JavaScript
1
2
1
[1, 10, 20, 59, 63, 8, 0, 0, 0]
2
But my desired output is:
JavaScript
1
2
1
[0, 0, 0, 1, 10, 20, 59, 63, 8]
2
Advertisement
Answer
JavaScript
1
8
1
output = []
2
for i in nums:
3
if i == 0:
4
output.insert(0, 0)
5
else:
6
output.append(i)
7
output
8