C++ Accepted Code


  • 42
    J
    void moveZeroes(vector<int>& nums) {
        int last = 0, cur = 0;
        
        while(cur < nums.size()) {
            if(nums[cur] != 0) {
                swap(nums[last], nums[cur]);
                last++;
            }
            
            cur++;
        }
    }

  • 0
    H

    if cur == last, there is no need to swap. The number of operations can be reduced.


  • 4
    M

    Same idea, with for loop

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

  • 0
    V

    it would be quite a big improvement


  • 0
    Y

    ^True, but you add operations in order to check that condition. Not sure if it's a worth while optimization overall.


  • 0
    M

    Can I use nums.erase(i) ?


  • 0
    J

    hmm... i don't exactly know what you are trying to do. you can write down the code here. but, i think whatever you do with nums.erase(i) the complexity would be worse than the code above.


  • 0
    I

    no longer accepted. too slow despite being good.


  • 1
    Z

    Not meet the conditions´╝ÜMinimize the total number of operations.


Log in to reply
 

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