力扣-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++;
        }
    }
}
相关推荐
Learner__Q4 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
阿昭L4 小时前
leetcode链表相交
算法·leetcode·链表
小南家的青蛙6 小时前
LeetCode第1261题 - 在受污染的二叉树中查找元素
算法·leetcode·职场和发展
玖剹6 小时前
记忆化搜索题目(二)
c语言·c++·算法·leetcode·深度优先·剪枝·深度优先遍历
Jul1en_8 小时前
【算法】分治-归并类题目
java·算法·leetcode·排序算法
java修仙传8 小时前
力扣hot100:寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
F_D_Z10 小时前
哈希表解Two Sum问题
python·算法·leetcode·哈希表
LYFlied10 小时前
【每日算法】LeetCode124. 二叉树中的最大路径和
数据结构·算法·leetcode·面试·职场和发展
小妖66612 小时前
力扣(LeetCode)- 93. 复原 IP 地址(JavaScript)
javascript·tcp/ip·leetcode
前端小白在前进14 小时前
力扣刷题:复原IP地址
tcp/ip·算法·leetcode