Leetcode283. Move Zeroes | Two Pointers

这篇博客介绍了一种解决将数组中所有0移动到末尾,同时保持非零元素相对顺序不变的问题的算法。通过双指针技巧,利用O(1)空间复杂度,每次只移动一个元素并更新指针位置。核心代码展示了如何在不使用额外数据结构的情况下完成操作。
摘要由CSDN通过智能技术生成
1. Description

There is an array nums size of n. We have to move all ‘0’ to the end and maintain the relative orders of non-zero elements. Space complexity must be O(1).

2.Algorithm

Two pointers

3.Analysis

O(1) space complexity means we can not use any data structures to assist. To maintain the relative order, every time we move a ‘0’ to the end, we let the element after this ‘0’ move forward by one step. Because the element after ‘0’ move forward, an empty seat appears in the end of the array. We just need to put ‘0’ in these empety seats in the end.
Notice that the type of function is void, so we do not need to return nums.

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int ap = 0, zp = 0;
        for(int i = 0; i < nums.size();i++){
            if(nums[ap] == 0){
                ap++;
            }
            else{
                nums[zp] = nums[ap];
                zp++;
                ap++;
            }
        }
        while(zp < nums.size()){
            nums[zp] = 0;
            zp++;
        }
    }
};
4.Complexity

TIme complexity: O(n)
Space complexity: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值