力扣-283. 移动零

文章目录

力扣题目

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

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

示例 1:

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

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

示例 2:

输入: nums = [0]

输出: [0]

代码

第一种做法

思路:将数组中不为0的数记下来,后边补0

c 复制代码
void moveZeroes(int* nums, int numsSize)
{
    int i = 0, index = 0;
    for(i = 0; i < numsSize; i++)
    {
        if(0 != nums[i])
        {
            nums[index] = nums[i];
            index++;
        }
    }

    while(index < numsSize)
    {
        nums[index] = 0;
        index++;
    }
}

第二种做法

利用双指针的思想,把不为0的数字挪到前边

c 复制代码
void Swap(int *num1, int *num2)
{
    int temp = *num1;
    *num1 = *num2;
    *num2 = temp;
}

void moveZeroes(int* nums, int numsSize) 
{
    int first = 0;
    int last = 1;
    if(1 == numsSize)
    {
        return;
    }   
    while(last < numsSize)
    {
        if(nums[first] == 0 && nums[last] != 0)
        {
            Swap(&nums[first], &nums[last]);
            first++;
            last++;
        }
        else if(nums[first] == 0 && nums[last] == 0)
        {
            last++;
        }
        else
        {
            first++;
            last++;
        }
    }
}
相关推荐
共享家952714 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi16 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
楼田莉子16 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon3416 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
轮到我狗叫了17 小时前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode
dragoooon3418 小时前
[优选算法专题二滑动窗口——串联所有单词的子串]
数据结构·c++·学习·算法·leetcode·学习方法
刃神太酷啦18 小时前
C++ 异常处理机制:从基础到实践的全面解析----《Hello C++ Wrold!》(20)--(C/C++)
java·c语言·开发语言·c++·qt·算法·leetcode
薰衣草233320 小时前
滑动窗口(2)——不定长
python·算法·leetcode
YuTaoShao1 天前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵
野犬寒鸦1 天前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode