Cover image for LeetCode Hot 100 P283 Move Zeroes

LeetCode Hot 100 P283 Move Zeroes

Words 240
Views
Visitors

Timeline

Timeline

2025-12-24

init

Two pointers

Problem:

Bubble sort approach:

123456789101112131415161718192021
#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 tail of the already processed sequence, and the right pointer points to the head of the sequence to be processed.
  • The right pointer keeps moving to the right. Each time it points to a non-zero number, swap the numbers at the left and right pointers, and also move the left pointer to the right.
123456789101112131415161718192021222324
#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++;                }        }};
Loading comments…