LeetCode 283. Move Zeroes 题解(C++)

来源:互联网 发布:手机淘宝网货到付款 编辑:程序博客网 时间:2024/05/17 08:36

LeetCode 283. Move Zeroes 题解(C++)


题目描述

  • Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

示例

  • For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
  • -

补充

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.

思路

解法1

  • 遍历数组,把数组非零的元素放到前面来。若该元素非0,则将该元素放置到lastNonZeroFoundAt指向的位置上,并使其自加1,遍历完该数组后,再在该数组lastNonZeroFoundAt位置及其后面补0.该算法空间复杂度为O(1),时间复杂度为O(n),对数组数字的操作次数为数组的长度n。

解法2

  • 遍历数组,把数组非零的元素与数组最前面的零元素进行交换。若该元素非0,则将该元素与数组最前面的零元素(lastNonZeroFoundAt指向的位置)交换。该算法的空间复杂度为O(1),时间复杂度为O(n),对数组数字的操作次数为数组非零元素的个数。

代码

解法1

class Solution {public:    void moveZeroes(vector<int>& nums)    {        int lastNonZeroFoundAt = 0;        for (int i = 0; i < nums.size(); ++i)        {            if (nums[i] != 0)            {                nums[lastNonZeroFoundAt++] = nums[i];            }        }        for (int i = lastNonZeroFoundAt; i < nums.size(); ++i)        {            nums[i] = 0;        }    }};

解法2

class Solution {public:    void moveZeroes(vector<int>& nums)    {        int lastNonZeroFoundAt = 0;        for (int i = 0; i < nums.size(); ++i)        {            if (nums[i] != 0)            {                swap(nums[i], nums[lastNonZeroFoundAt++]);            }        }    }};
0 0
原创粉丝点击