283. Move Zeroes(双指针)

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
class Solution {
public:
    //双指针
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();
        if(n <= 1) return ;
        int i=0,j=0;
        while(i<n&&j<n){
            while(i<n && nums[i]) i++;
            //遇到nums[i]为0
            j = i+1;
            while(j<n && !nums[j]) j++;
            //遇到nums[j]非0
            if(j<n) swap(nums[i],nums[j]);
        }
        return ;
    }
};
原文地址:https://www.cnblogs.com/wsw-seu/p/14002872.html