mariia-kornieva
8/23/2019 - 7:57 PM

283. Move Zeros

  1. Move Zeros
// Optimal in space; Sub-optimal in time;
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int last = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] != 0) {
                nums[last++] = nums[i];
            }
        }
        for (int i = last; i < nums.size(); ++i) {
            nums[i] = 0;
        }
    }
};

// Optimal in time and space
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for (int last = 0, cur = 0; cur < nums.size(); ++cur) {
            if (nums[cur] != 0) {
                std::swap(nums[last++], nums[cur]);
            }
        }
    }
};

// C++ algorithms
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        std::stable_partition(std::begin(nums), std::end(nums), [](int n){
            return n != 0;
        });
    }
};