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.
Problem Solving Ideas:
Topics can be solved within O (n) Time complexity
Algorithm steps: x = i y = j
Use two "pointers" X and y, initial order y = 0
Use X to iterate through the array nums:
If NUMS[X] is not 0, then Exchange Nums[x] and Nums[y], and make y+1
Simple analysis of the algorithm:
The Y pointer points to the location where the first 0 elements may exist
During traversal, the algorithm ensures that elements in the [Y, X] range are 0
Java Code
Public void movezeroes (int[] nums) { int i = 0, j = 0; for (i = 0; i< nums.length; i++) { if(nums[i]! = 0) {if(j! = i) { = nums[i]; = 0; } J+ +;}}}
Reference:
1. http://bookshadow.com/weblog/2015/09/19/leetcode-move-zeroes/
2. Https://leetcode.com/discuss/59543/move-zeros-solution-in-java
Leetcode Move Zeroes