Last active
September 29, 2015 20:37
-
-
Save lyleaf/bdc7a0d4f76d6fb1c5ce to your computer and use it in GitHub Desktop.
Move-Zeroes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void moveZeroes(vector<int>& nums) { | |
for (int i = 0, j = 0; i < nums.size(); i++) { | |
if (nums[i] != 0) swap(nums[i], nums[j++]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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