力扣-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++;
        }
    }
}
相关推荐
小年糕是糕手9 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
sheeta199814 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!1 天前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi1 天前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
-森屿安年-1 天前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
元亓亓亓1 天前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
2501_941143731 天前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
Elias不吃糖1 天前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
野蛮人6号1 天前
力扣热题100道前62道,内容和力扣官方稍有不同,记录了本人的一些独特的解法
数据结构·算法·leetcode