问题描述
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].
思路1:先找出所有的0并将0保存在一个新的数组里,同时删除原数组中的0。最后将新数组拼接到原数组后面
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
var arr = new Array();
for( var i = 0; i < nums.length; i++){
if(nums[i] === 0){
arr.push(nums[i]);
nums.splice(i,1);
i--;
}
}
for(var j = 0; j < arr.length; j++) {
nums.push(arr[j]);
}
};
思路2:通过改变数组的下标来保存不为0 的值,同时记得将不为0的元素替换为0,。
var moveZeroes = function(nums) {
var c1=0;
for(var i=0;i<nums.length;i++){
if(nums[i]!==0){
if(c1!=i){
nums[c1]=nums[i];
nums[i]=0;
}
c1++;
}
}
};