Leetcode学习笔记:#283. Move Zeroes
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.
实现:
public void moveZeroes(int[] nums){
if(nums == null || nums.length == 0)
return;
int insertPos = 0;
for(int num : nums){
if(num != 0) nums[insertPos++] = num;
}
while(insertPose < nums.length){
nums[insertPos++]=0;
}
}
思路:
用一个insertPos来记录非0的数字有多少个,遍历整个数组,把非0数字排在前面,再把Insertpos与数组长度比较,少于数组长度的则是0的个数。