标签:
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.
Two pointer l,r,
l is to find each 0 in the list, r is to start from l, find first non-0
l, r should not both start from 0, because if r is to the left of l, we don‘t want to swap it. example: [1, 0]
1 public class Solution { 2 public void moveZeroes(int[] nums) { 3 if (nums==null && nums.length==0) return; 4 int l=0, r=0; 5 while (l < nums.length && r < nums.length) { 6 while (l<nums.length && nums[l]!=0) { 7 l++; 8 } 9 r = l; 10 while (r<nums.length && nums[r]==0) { 11 r++; 12 } 13 if (l == nums.length || r == nums.length) break; 14 swap(nums, l, r); 15 } 16 } 17 18 public void swap(int[] nums, int l, int r) { 19 int temp = nums[l]; 20 nums[l] = nums[r]; 21 nums[r] = temp; 22 } 23 }
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5077606.html