LeetCode 283: Move Zeroes
LeetCode 283: Move Zeroes
题意描述
给定一个数组num,编写一个函数,将所有0移到它的末尾,同时保持非零元素的相对顺序。
注:(1)不能复制数组
(2)尽可能少的移动数组元素
解题思路
一、思路一
- 遍历数组,使用一个临时变量记录第一个0的位置J
- 如果J后面的元素非0则进行交换,更新J的索引
- 如果J后面的元素为0,则继续向后遍历,直到遇到非0的元素,与J交换位置,更新J的索引,J指向第二个0
- 遍历数组结束,J指向最后一个0,并且前面的0已经移动到最后一个0后面
public void moveZeroes(int[] nums) {
int j = 0;
for(int i=0;i<nums.length;i++){
if(nums[i] != 0){
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}
二、思路二
- 遍历数组,使用count记录遍历过程中0的个数
- 如果nums【i】不为0,则向前移动count位
- 将数组后count位置0
public void moveZeroes(int[] nums) {
int count = 0;
int len = nums.length;
for(int i=0;i<len;i++){
if(nums[i] == 0) count ++;
if(nums[i] != 0) nums[i-count] = nums[i];
}
for(int i=0;i<count;i++){
nums[len-count+i] = 0;
}
}