#include <iostream>
#include <vector>
using namespace std;
/*
感觉这种方法做了很多重复工,不好
*/
/*
class Solution {
public:
void moveZeroes(vector<int>& nums) {
//找到可以插入的位置
int tag = 0;
for (int i = 0; i < nums.size(); i++) {
if (i != tag) {
nums[tag] = nums[i];
}
//非0不能插入,+1;0可以插入,不动
if (nums[i] != 0) {
tag++;
}
}
//补0
for (int i = tag; i < nums.size(); i++) {
nums[i] = 0;
}
}
};*/
//感觉这个好一点
class Solution {
public:
void moveZeroes(vector<int>& nums) {
//找到可以插入的位置
int tag = 0;
for (int i = 0; i < nums.size(); i++) {
if (i != tag) {
if (nums[i] != 0) {
nums[tag] = nums[i];
nums[i] = 0;
tag++;
}
} else {
if (nums[i] != 0) {
tag++;
}
}
}
}
};
int main(int argc, const char * argv[]) {
vector<int> n = {0,1,0,3,12};
Solution s;
s.moveZeroes(n);
for (int i = 0; i < n.size(); i++) {
cout << n[i] << " ";
}
cout << endl;
return 0;
}leetcode-283-Move Zeroes
最新推荐文章于 2022-06-27 14:37:23 发布
本文介绍了一种用于将整型数组中所有零元素移至末尾的算法实现,并提供了两种不同的解决方案。通过遍历数组,非零元素向前移动,随后填充零元素到数组尾部,以此完成任务。
222

被折叠的 条评论
为什么被折叠?



