Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for_each(remove(begin(nums), end(nums), 0), end(nums),
[](int& x) { x = 0; });
}
};
01034 => 将 134 覆盖到开头 => 13434 => 返回第二个 3 的位置
对返回位置及其之后位置置零 => 13400
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int l = 0;
int cur = 0;
while (cur < size(nums)) {
if (nums[cur] == 0) {
++cur;
} else {
nums[l++] = nums[cur++];
}
}
for (int i = l; i < size(nums); ++i) {
nums[i] = 0;
}
}
};