营销型网站四大元素电商seo优化是什么
题目
给定一个数组 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(vector<int>& 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(vector<int>& nums) {int t = 0; // 用于统计数组中 0 的个数// 遍历数组,统计 0 的个数for (auto i : nums) {if (i == 0) {t++; // 如果当前元素是 0,计数器 t 加 1}}// 使用 remove 和 erase 删除所有 0// remove 将非 0 元素移动到数组前面,并返回新的逻辑结尾// erase 删除从新结尾到原结尾的所有元素(即删除所有 0)nums.erase(remove(nums.begin(), nums.end(), 0), nums.end());// 在数组末尾添加 t 个 0for (int i = 0; i < t; i++) {nums.push_back(0);}}
};