Leetcode Note: Move Zeroes
I. Description
Given an array nums, write a function to move all0'sTo the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [0, 1, 0, 3, 12], After calling your function, nums shoshould be[1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array. Minimize the total number of operations.
Ii. Question Analysis
The meaning of the question is very clear. Given an array, adjust the non-zero element to the front, and place the zero element behind the array. In-situ operations are required and as few operations as possible.
The question is relatively simple. You only need to scan the array once and use an integer variable in this process.IndexRecords the number of non-zero elements. Each time a non-zero number is encountered, it is placed innums[Index]And thenIndexAdd1.
After the traversal,numsThe position of the non-zero element has been determined. You only need to set the half of the array to zero.IndexRecords the number of non-zero elements, so it is convenient to set the value to zero.
Iii. Sample Code
class Solution {public: void moveZeroes(vector
& nums) { if (nums.size() < 1) return; int Index = 0; for (int i = 0; i < nums.size(); ++i) if (nums[i] != 0) nums[Index++] = nums[i]; for (;Index < nums.size(); ++Index) nums[Index] = 0; }};
Iv. Summary
For such problems, in-situ operations and as few operations as possible are generally required.