Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Last active September 29, 2015 20:37
Show Gist options
  • Save lyleaf/bdc7a0d4f76d6fb1c5ce to your computer and use it in GitHub Desktop.
Save lyleaf/bdc7a0d4f76d6fb1c5ce to your computer and use it in GitHub Desktop.
Move-Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
#XIAOMENG
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
n = 0
for i in xrange(l):
if nums[i]==0:
n+=1
else:
temp = nums[i-n]
nums[i-n] = nums[i]
nums[i] = temp
void moveZeroes(vector<int>& nums) {
for (int i = 0, j = 0; i < nums.size(); i++) {
if (nums[i] != 0) swap(nums[i], nums[j++]);
}
}
#My Solution
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
a = []
n = 0
for i,j in enumerate(nums):
if j==0:
n+=1
a.append(-1)
else:
a.append(n)
for i,x in enumerate(a):
if x != -1:
nums[i-x]=nums[i]
if x!=0:
nums[i]=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment