Cover image for LeetCode Hot 100 P283 Move Zeroes

LeetCode Hot 100 P283 Move Zeroes


Timeline

timeline

2025-12-24

init

two pointers

Title:

Bubble sort approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using std::vector;

class Solution {
public:
void moveZeroes(vector<int> &nums)
{
int i = 0, j = 0, n = nums.size();
int k = n - 1;
for (i = n-1; i >= 0; i--) {
if (nums[i] == 0) {
j = i;
while (nums[j] == 0 && j < k) {
std::swap(nums[j], nums[j + 1]);
j++;
}
k--;
}
}
}
};

Two pointers:

  • The left pointer points to the end of the already processed sequence, and the right pointer points to the beginning of the sequence to be processed.
  • The right pointer keeps moving to the right. Each time the right pointer points to a non-zero number, swap the numbers at the left and right pointers, and move the left pointer to the right.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <vector>
using std::vector;

class Solution {
public:
void moveZeroes(vector<int> &nums)
{
int n = nums.size(), left = 0, right = 0;
while (left < n && nums[left] != 0) {
left++;
}
right = left;
while (right < n && nums[right] == 0) {
right++;
}
while (right < n) {
if (nums[right] != 0) {
std::swap(nums[left], nums[right]);
left++;
}
right++;
}
}
};