【力扣 283】移动零 C++题解(向量+循环)

50 阅读1分钟

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2:

输入: nums = [0] 输出: [0]

提示:

1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1

进阶:你能尽量减少完成的操作次数吗?


思路

首先定义了一个计数器cnt,用来记录nums中零的数量。然后,函数定义了一个迭代器it1,用来遍历nums

在遍历过程中,如果迭代器指向的元素是零(即!*it1为真),那么就使用erase函数将这个元素从nums中删除,并将删除元素后的新位置赋值给it1,同时将cnt加一。如果迭代器指向的元素不是零,那么就将迭代器向后移动一位。

遍历结束后,cnt的值就是nums中零的数量,而nums中的所有零都已经被删除。然后,函数使用push_back函数将cnt个零添加到nums的末尾。


AC代码

/*
 * @lc app=leetcode.cn id=283 lang=cpp
 *
 * [283] 移动零
 */

// @lc code=start
class Solution {
   public:
	void moveZeroes(vector<int>& nums) {
		int cnt = 0;
		auto it1 = nums.begin();
		for (; it1 != nums.end();) {
			if (!*it1) {
				it1 = nums.erase(it1);
				cnt++;
			} else {
				it1++;
			}
		}
		for (int i = 1; i <= cnt; i++) {
			nums.push_back(0);
		}
	}
};
// @lc code=end