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. = [0, 1, 0, 3, a], after calling your function, nums should be [1, 3, a, 0, 0 do this in-Placewithout making a copy of the array. Minimize The total number of operations.
Pointer L,r,
L was to find each 0 in the list, and R is to start from L, find first non-0
L, R should not both start from 0, because if R was to the left of L, we don ' t want to swap it. Example: [1, 0]
1 Public classSolution {2 Public voidMovezeroes (int[] nums) {3 if(nums==NULL&& nums.length==0)return;4 intL=0, r=0;5 while(L < nums.length && R <nums.length) {6 while(L<nums.length && nums[l]!=0) {7l++;8 }9R =l;Ten while(R<nums.length && nums[r]==0) { Oner++; A } - if(L = = Nums.length | | r = = nums.length) Break; - Swap (Nums, L, R); the } - } - - Public voidSwapint[] Nums,intLintr) { + inttemp =Nums[l]; -NUMS[L] =Nums[r]; +NUMS[R] =temp; A } at}
Leetcode:move Zeroes