Given an array nums , write a function to move all's to the 0 end of it while maintaining the relative order of the No N-zero elements.
For example, given nums = [0, 1, 0, 3, 12] , after calling your function, nums should is [1, 3, 12, 0, 0] .
Note:
- You must does this in-place without making a copy of the array.
- Minimize The total number of operations.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
This problem lets us move all 0 of a given array to the back, the non-zero forward, the request cannot change the relative position of the non-zero, and cannot copy the additional array, then can only use the substitution method in-place to do, need to use two pointers, a non-stop backward sweep, find nonzero position, Then swap the position with the previous pointer, see the following code:
class Solution {public: void movezeroes (vector<int>& Nums) { for (int00; i < nums.size (); + +i) { if (Nums[i]) { swap (nums[i], nums[j+ +]);}}} ;
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Move Zeroes Zero