LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  void moveZeroes(vector<int>& nums) {
    for_each(remove(nums.begin(), nums.end(), 0), nums.end(),
             [](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 < nums.size()) {
      if (nums[cur] == 0) {
        ++cur;
      } else {
        nums[l++] = nums[cur++];
      }
    }
    for (int i = l; i < nums.size(); ++i) {
      nums[i] = 0;
    }
  }
};