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].這道題的意思就是將一個數組裏面的全部0移到數組的最後,同時要保持數組的非零元素順序不變數組
同時這道題也有額外的要求:不能聲明一個新的拷貝的數組以及儘可能減小操做的次數code
public void moveZeroes(int[] nums) { if(nums != null && nums.length == 0) return; int insertPost = 0; for(int num : nums){ if(num != 0){ nums[insertPost++] = num; } } while(insertPost < nums.length){ nums[insertPost++] = 0; } }