LeetCode283——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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

实现:
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        vector<int>& vec = nums;
        int np = 0;
    int zp = 0;
    while (zp < vec.size() && np < vec.size()) {
    while (vec[zp] != 0 ) zp++;
    while (vec[np] == 0 || np <= zp) np++;
    if (zp >= vec.size() || np >= vec.size()) {
    break;
    }
    std::swap(vec[zp], vec[np]);
    zp++; np++;
    }
    }
};

你可能感兴趣的:(LeetCode,面试题)