Given an array nums, write a function to move all 0 's to the end of it while maintaining the relative order of the Non-zer o elements.
For example, given nums = [0, 1, 0, 3, and 1], after calling your function, Nums should is [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.
Moving all 0 of an array to the back, cannot change the relative positional relationship of non-zero, and cannot copy additional arrays.
To use the substitution method In-place, double pointer to do, the front pointer to the last non-0 number of processing, the back of a pointer to sweep backward, encountered a non-0 number, and the front pointer refers to the digital exchange position, the front pointer moves 1 bits behind.
Or do not exchange only the non-zero number to the front, the final unification of the back of all into 0.
Java:time complexity:o (n), Space complixity:o (1)
public class Solution {public void Movezeroes (int[] nums) { int index = 0; for (int i = 0; i < nums.length; ++i) { if (nums[i]! = 0) { nums[index++] = nums[i]; } } for (int i = index; i < nums.length; ++i) { nums[i] = 0;}}}
Python:
Class solution (Object): def movezeroes (self, Nums): "" " : Type Nums:list[int] : Rtype:void does not Return anything, modify Nums in-place instead. "" pos = 0 for i in Xrange (Len (nums)): if nums[i]: nums[i], nums[pos] = Nums[pos], Nums[i] pos + = 1
C++:
Class Solution {public: void Movezeroes (vector<int>& nums) { int pos = 0; for (auto& num:nums) { if (num) { swap (nums[pos++], num);}}} ;
[Leetcode] 283. Move Zeroes Zero