3 different solutions


  • 0
    // might have unneeded writing (one pass)
    void moveZeroes(vector<int>& nums) {
      int pointer = 0;
      for (int num : nums)
        if (num) nums[pointer++] = num;
    }
    
    // do not preserve non-zero order (one pass): this does not satisfy the reuirement by OJ
    void moveZeroes(vector<int>& nums) {
      int i = 0, j = nums.size()-1;
      while (i < j) {
        if (nums[i]) ++i;
        else if (!nums[j]) --j;
        else swap(nums[i++], nums[j--]);
      }
    }
    
    // preserve non-zero order and minimum writing (two passes)
    void moveZeroes(vector<int>& nums) {
      int i = 0, j = 0;
      while (i < nums.size()-1 && j < nums.size()) {
        if (nums[i]) j = ++i;
        else if (!nums[j]) ++j;
        else swap(nums[i++], nums[j++]);
      }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.