-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathmove_zeros.cpp
More file actions
37 lines (33 loc) · 788 Bytes
/
move_zeros.cpp
File metadata and controls
37 lines (33 loc) · 788 Bytes
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
#include "vector"
#include "iostream"
using namespace std;
class Solution {
public:
// 移动零
void moveZeroes1(vector<int>& nums) {
int i = 0, j = 0;
for (; j < nums.size(); j++)
{
if (nums[j] != 0)
{
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
i++;
}
}
}
// 先将不为零的位置填充,剩下的就是0
void moveZeroes2(vector<int>& nums) {
int start = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] != 0) {
nums[start++] = nums[i];
}
}
for (; start < nums.size(); start++) {
nums[start] = 0;
}
}
};