LC.283.Move Zeroes

https://leetcode.com/problems/move-zeroes/description/
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-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

 1 //normal way of doing it:time: O(n) space: O(1)
 2     public void moveZeroes(int[] nums) {
 3         //corner cases:
 4         if(nums == null || nums.length == 0) return ;
 5         //two pointers: i: non-zero index-slow  j: normal index counter-faster
 6         int i =0, j = 0 ;
 7         while(j<nums.length){
 8             if (nums[j]==0){
 9                 j++;
10             }else{
11                 nums[i] = nums[j] ;
12                 i++ ;
13                 j++;
14             }
15         }
16         /*
17         * add all the trailing 0: tricky part is from i or from i+1?
18         * in this case, we could use some example to help
19         * [0 1 0 0  2]  [ 1 2 000] i =2, so we should use i to length
20          * */
21         for (int k = i; k < nums.length ; k++) {
22             nums[k] = 0 ;
23         }
24     }

 

 1 /*
 2     this is used for the case lots of zero:
 3     time complexity: 2(swap) * # of non-zero  ~ o(#of non-zero)
 4     * */
 5     public void moveZeros2(int[] nums){
 6         //corner cases:
 7         if(nums == null || nums.length == 0) return ;
 8         //two pointers: i: (-inf, i) non-zero, i is the 1st index zero (slow)  j: normal index counter-faster
 9         int i =0, j =0 ;
10         while (j<nums.length){
11             //when j is non-zero, swap with i
12             if (nums[j] != 0){
13                 int temp = nums[j] ;
14                 nums[j] = nums[i]; //i is the 1st index zero
15                 nums[i] = temp;
16                 i++;
17             }
18             j++;
19         }
20     }

 

原文地址:https://www.cnblogs.com/davidnyc/p/8553329.html