须臾 .  
恍若断崖独坐凝望蓝色海面心平如镜

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。
 1 /**
 2  * @param {number[]} nums
 3  * @return {void} Do not return anything, modify nums in-place instead.
 4  */
 5 var moveZeroes = function(nums) {
 6     for(var i = 0;i < nums.length;i++){
 7         if(nums[i] === 0){
 8            zIndexTop(nums,i,nums.length);
 9         }
10     }
11 };
12 function swapArray(arr, index1, index2) {
13    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
14     return arr;
15 }
16 function zIndexTop(arr,index,length){
17    if(index+1 != length){
18       var moveNum = length - 1 - index;
19        for (var i = 0; i<moveNum; i++) {
20          swapArray(arr, index, index + 1);
21           index++;
22      }
23    }
24 }

 

 
posted on 2018-10-30 09:09  须臾_/  阅读(133)  评论(0)    收藏  举报