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.
Title Tags: Array, pointers
The topic gave us a nums array, let's move all 0 to the last side and keep the other numbers sorted.
Using the Pointers P1 and P2, the basic idea is to let the P2 stay in the 0 number, let P1 find not 0 of the number, swap P1 p2 value.
Traversing the nums array, when encountering 0 words, p1++, when encountering numbers that are not 0, swap P1 and P2 values, p1++ p2++.
Java Solution:
Runtime beats 74.14%
Completion Date: 04/27/2017
Key words: Array, pointers
Key point: Find a number that is not 0, with 0 permutation
1 Public classSolution2 {3 Public voidMovezeroes (int[] nums)4 {5 intP1 = 0;//Iterate each number6 intP2 = 0;//stop at 07 8 while(P1 <nums.length)9 {Ten if(NUMS[P1]! = 0)//Find the Non-zero number One { A if(P1! = p2)//swap Non-zero number with zero number -{//if p1 = p2, no need to swap - inttemp =NUMS[P1]; theNUMS[P1] =NUMS[P2]; -NUMS[P2] =temp; - } - +p2++; - } + Ap1++; at } - - } -}
Reference: N/A
Leetcode algorithm topic List- leetcode algorithms Questions list
Leetcode 283. Move zeroes (mobile 0)