-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmovezero.cpp
More file actions
42 lines (39 loc) · 1.06 KB
/
movezero.cpp
File metadata and controls
42 lines (39 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution
{
public:
void moveZeroes(vector<int>& dump)
{
//使用双指针,第一个指针代表不为零的元素的最终位置
//第二个代表从头开始遍历
int nonZeroIndex = 0;
for(int i = 0;i < dump.size();i++)
{
//i就是我们要的第二个指针
//如果某一位不等于0,那么就把他前移和交换(不用管后面的)
if(dump[i] != 0)
{
//先使用值,再进行自增1,这一个需要注意
dump[nonZeroIndex++] = dump[i];
}
}
// 此时的数组已经处理好,把nonZeroIndex后面的所有元素化成零即可
for (int i = nonZeroIndex; i < dump.size(); i++)
{
dump[i] = 0;
}
}
};
int main()
{
Solution test;
vector<int> test2 = {0,1,0,3,12};
test.moveZeroes(test2);
for(int i = 0;i < test2.size();i++)
{
cout << test2[i] << endl;
}
}