【LeetCode】283. Moving Zero (C++)

1 topic description

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

2 Example description

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

3 Problem solving instructions

1. You must operate on the original array, and cannot copy additional arrays.
2. Minimize the number of operations.

4 Problem-solving ideas

Open two subscripts, if the array traversal is not equal to 0, move forward, if equal to 0, do not operate, and finally add 0.

5 Detailed source code (C++)

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

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114434803