[Primary Algorithm] 8. Move Zero

topic:

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

For example, define nums = [ 0 , 1 , 0 , 3 , 12 ], after calling the function, nums should be [ 1 , 3 , 12 , 0 , 0 ].

Precautions:

Must operate on the original array, do not allocate extra space for a new array.
Minimize the total number of operations.
 

Contributor:
Special thanks to @jianchao.li.fighter for adding this question and creating all the test cases.

1. Problem solving ideas:

This question is relatively simple, just set a double pointer, cur points to all non-zero elements, and next is the next element of the traversed array. After the array is traversed, the related function implementation can be completed.

 

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325293133&siteId=291194637