-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmove-zeroes.cpp
More file actions
28 lines (24 loc) · 792 Bytes
/
Copy pathmove-zeroes.cpp
File metadata and controls
28 lines (24 loc) · 792 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
/* https://leetcode.com/problems/move-zeroes/ */
class Solution {
public:
void moveZeroes(vector<int>& nums) {
const int len = nums.size();
int zeroIndex = 0, nonZeroIndex = 1;
if (len == 1) return;
if (len == 2) {
if (nums[0] == 0 && nums[1] != 0)
swap(nums[0], nums[1]);
return;
}
while (nonZeroIndex < len) {
if (nums[nonZeroIndex] == 0 && nums[zeroIndex] == 0) {
nonZeroIndex++;
} else if (nums[zeroIndex] == 0 && nums[nonZeroIndex] != 0) {
swap(nums[nonZeroIndex], nums[zeroIndex]);
nonZeroIndex++; zeroIndex++;
} else {
nonZeroIndex++; zeroIndex++;
}
}
}
};