力扣-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++;
        }
    }
}
相关推荐
代码小将27 分钟前
力扣992做题笔记
算法·leetcode
编程绿豆侠30 分钟前
力扣HOT100之二叉树:199. 二叉树的右视图
算法·leetcode·职场和发展
飞川撸码1 小时前
【LeetCode 热题100】17:电话号码的字母组合(详细解析)(Go语言版)
算法·leetcode·golang·dfs
蒟蒻小袁1 小时前
力扣面试150题--从前序与中序遍历序列构造二叉树
算法·leetcode·面试
鸡鸭扣4 小时前
leetcode hot100:解题思路大全
数据结构·python·算法·leetcode·力扣
June`5 小时前
专题五:floodfill算法(太平洋大西洋水流问题)
c++·算法·leetcode·深度优先·剪枝
exe4527 小时前
力扣每日一题5-19
java·算法·leetcode
ganjiee00077 小时前
leetcode 每日一题 1931. 用三种不同颜色为网格涂色
windows·python·leetcode
freyazzr10 小时前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
freyazzr10 小时前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论