原地算法之将数组中的指定元素,移动到数组的尾部

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

示例:

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

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。
 
class Solution {
    public void moveZeroes(int[] nums) {
        int index=0;//非零个数
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                nums[index++]=nums[i];  
            }        
        }
        while(index<nums.length){
            nums[index++]=0;
        }
    }
}

这个和上一篇的从数组中删除指定元素类似:

1)定义一个计数标志,记录非零元素的个数;

2)并将这个计数器作为移动后顺序的下标保存移动后的数据;

3)最后将下标以后的元素设置为0

猜你喜欢

转载自www.cnblogs.com/raychou1995/p/10236196.html