题目链接
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.
Example:
Input: [0,1,0,3,12]
Output: [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.
python实现:
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
arr = []
for i in nums:
if i != 0:
arr.append(i)
for i in range(len(nums) - len(arr)):
arr.append(0)
nums[:] = arr[:]
JavaScript实现:
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let arr = []
for(i in nums){
if(nums[i] != 0){
arr.push(nums[i])
}
}
len = nums.length-arr.length
for(let i=0;i<len;i++){
arr.push(0)
}
for(let i=0;i<arr.length;i++){
nums[i] = arr[i]
}
return nums
};
var res = moveZeroes([0,1,0,3,12])
console.log(res)