LeetCode链接:283. 移动零 - 力扣(LeetCode)
思路一:利用双指针,指针i和指针j都指向索引0,遍历数组,当遇到非0的元素时,将array[j]存入到array[i++]中,最后再遍历[i,array.length]并赋值为0
java代码:
class solution{
public void moveZeroes(int[] nums){
if(nums == null) return;
int n = nums.length;
int i = 0;
for(int j = 0; j < n; j++){
if(nums[j] != 0){
nums[i++] = nums[j];
}
}
for(int j = i; j < n; j++){
nums[j] = 0;
}
}
}
思路二:指针i和指针j指向索引0,遍历数组,当遇到array[j] != 0时候交换指针i和指针j所在的位 置,并使i++
java代码:
class solution{
public void moveZero(int[] nums){
if(nums == null) return;
int n = nums.length;
int i = 0;
for(int j = 0; j < n; j++){
if(nums[j] != 0){
int temp = nums[j]
nums[j] = nums[i];
nums[i++] = temp;
}
}
}
}