北京企业网站报价,深圳建设管理中心网站,公司网站建设开发,河南seo网站开发题目 给定一个数组 nums#xff0c;编写一个函数将所有 0 移动到数组的末尾#xff0c;同时保持非零元素的相对顺序。 请注意 #xff0c;必须在不复制数组的情况下原地对数组进行操作。 示例 1: 输入: nums [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2: 输入: nums [0] 输出…题目 给定一个数组 nums编写一个函数将所有 0 移动到数组的末尾同时保持非零元素的相对顺序。 请注意 必须在不复制数组的情况下原地对数组进行操作。 示例 1: 输入: nums [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2: 输入: nums [0] 输出: [0] 来源力扣热题100 283. 移动零 思路注意事项
学习remove()函数的用法 纯代码
class Solution {
public:void moveZeroes(vectorint nums) {int t 0;for (auto i : nums)if (i 0) t ;nums.erase(remove (nums.begin(), nums.end(), 0), nums.end());for (int i 0; i t; i ) nums.push_back(0);}
};题解加注释
class Solution {
public:void moveZeroes(vectorint nums) {int t 0; // 用于统计数组中 0 的个数// 遍历数组统计 0 的个数for (auto i : nums) {if (i 0) {t; // 如果当前元素是 0计数器 t 加 1}}// 使用 remove 和 erase 删除所有 0// remove 将非 0 元素移动到数组前面并返回新的逻辑结尾// erase 删除从新结尾到原结尾的所有元素即删除所有 0nums.erase(remove(nums.begin(), nums.end(), 0), nums.end());// 在数组末尾添加 t 个 0for (int i 0; i t; i) {nums.push_back(0);}}
};