[leetcode]Move zeros 慢方法和快方法

慢方法

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for(int i = 0;i != nums.size();++i){
            if(nums[i] == 0){
                for(int j = i + 1;j != nums.size();++j){
                    if(nums[j] != 0){
                        change(nums[i],nums[j]);break;}
                }
            }
        }
    }

private:
    void change(int& a,int& b){
        int tem = a;
        a = b;
        b = tem;
    }
};

快方法

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        size_t pos = 0;
        for(size_t i = 0;i != nums.size();++i){
            if(nums[i] != 0) nums[pos++] = nums[i];
        }
        for(;pos != nums.size();++pos)
            nums[pos] = 0;
    }
};

你可能感兴趣的:(算法)