283. Move Zeroes
View on LeetCode ↗
C++
class Solution {public: void moveZeroes(vector<int>& nums) { int j = 0; int i = 0; while (j < nums.size()) { if (nums[j] != 0) { swap(nums[i], nums[j]); i++; } j++; } }};
took me 15 minutes, should have been a three minute thing. I had at first gotten together a two pointer solution but i botched that by trying to do a for loop and a one pointer 0 end keeper. it worked in separating the 0s but failed in keeping order of the numbers.
The proper way of doing this is the solution above. i and j separate the entire thing into three parts so everything before i is normal numbers, i to j is 0s and j after are dirty numbers that are ingested into the if statement. if its not 0, move the number from j to the front i. this means that the 0s are not in order but this is just like the 0s are moveing through the array like a snake. now that makes more sense to me.
[0, i): confirmed non-zero elements, in original relative order.[i, j): confirmed zeros.[j, size): unexamined — could be zero or non-zero, you just haven't looked yet. ("Dirty" is a fine word for "unprocessed," just don't read it as "all zeros" — that's not guaranteed untiljpasses it.)