力扣-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++;
        }
    }
}
相关推荐
一匹电信狗21 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
墨染点香1 天前
LeetCode 刷题【43. 字符串相乘】
算法·leetcode·职场和发展
Keying,,,,1 天前
力扣hot100 | 矩阵 | 73. 矩阵置零、54. 螺旋矩阵、48. 旋转图像、240. 搜索二维矩阵 II
python·算法·leetcode·矩阵
_不会dp不改名_1 天前
leetcode_42 接雨水
算法·leetcode·职场和发展
code小毛孩1 天前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
快去睡觉~2 天前
力扣400:第N位数字
数据结构·算法·leetcode
gzzeason2 天前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
qq_513970442 天前
力扣 hot100 Day74
数据结构·算法·leetcode
墨染点香2 天前
LeetCode 刷题【42. 接雨水】
算法·leetcode·职场和发展
এ᭄画画的北北2 天前
力扣-347.前K个高频元素
算法·leetcode