LeetCode 283 移动零

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

示例:

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

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。

相关话题:数组;双指针

相似题目:27.移动元素

解题思路:

  1. 设置两个指针,一个指向当前节点,一个指向最后一个节点;
  2. 当前节点指针从后往前遍历,
  3. 当前节点元素值为0的时候,计算当前节点与最后节点之间的距离
  4. 以两个节点的距离作为上限,遍历数组,将当前节点的后面一个元素的值拷贝给当前节点
  5. 最后节点的元素值置零
  6. 最后节点前移。
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int distance = 0;
        int lastIndex = nums.size() - 1;
        for(int currentIndex = nums.size() - 1; currentIndex >= 0; currentIndex--){
            if(nums[currentIndex] == 0){
                distance = lastIndex - currentIndex;
                for(int i = 0 ;i < distance; i++){
                    nums[currentIndex + i] = nums[currentIndex + i + 1];
                }
                nums[lastIndex]= 0;
                lastIndex--;
            }
        }
    }
};
void moveZeroes(int* nums, int numsSize) {
    int currentIndex = numsSize - 1;
    int lastIndex = numsSize - 1;
    int distance = 0;
    while(currentIndex >= 0){
        if(nums[currentIndex] == 0){
            distance = lastIndex - currentIndex;
            for(int i = 0; i < distance; i++){
                nums[currentIndex + i] = nums[currentIndex + i + 1];
            }
             nums[lastIndex] = 0;
            lastIndex--;
        }
        currentIndex--;
    }
}

技术要点:双指针,从后遍历数组

总结:对于移动数组元素之类的操作,尤其是不能创建新的存储空间时候,使用双指针和从后向前遍历数组不失为一种有效的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值