创见博客
移动零
七崽爱吃小饼干2026/01/26阅读 0专栏 算法合集

移动零

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

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

codeType
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

示例 2:

codeType
输入: nums = [0]
输出: [0]

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

进阶:你能尽量减少完成的操作次数吗?

解法

ts
/**
 Do not return anything, modify nums in-place instead.
 */
function moveZeroes(nums: number[]): void {
    const n = nums.length
    let p1 = 0, p2 = 0 // 一个指针负责找0,一个指针负责找非0数,找到以后就交换值
    while(p2 < n){
        if(nums[p1] !== 0){
            p1++
            p2++
        }else{
            while(nums[p2] === 0){
                p2++
            }
            if(p2 >= n) return
            // 交换值
            nums[p1] = nums[p2]
            nums[p2] = 0
        }
    } 
};
评论
0/100