题目链接
题解:
思路一:交换
class Solution {
public void moveZeroes(int[] nums) {
int firstZero = 0;
boolean isMatchZero = false;
for(int i = 0;i < nums.length;i++){
if(!isMatchZero && nums[i] == 0){
firstZero = i;
isMatchZero = true;
}
if(nums[i] != 0){
swap(nums,i,firstZero);
firstZero++;
}
}
}
public static void swap(int[] arr,int i,int j){
if(arr[i] == arr[j]){
return;
}
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
}
执行结果:
思路二:覆盖
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for(int i = 0;i < nums.length;i++){
if(nums[i] != 0){
nums[j] = nums[i];
if(i != j){
nums[i] = 0;
}
j++;
}
}
}
}
执行结果:
思路三:滚雪球
class Solution {
public void moveZeroes(int[] nums) {
snowBall(nums);
}
private void snowBall(int[] nums){
int ballSize = 0;
for(int i = 0;i < nums.length;i++){
if(nums[i] == 0){
ballSize++;
}
if(nums[i] != 0 && ballSize > 0){
nums[i - ballSize] = nums[i];
nums[i] = 0;
}
}
}
}
执行结果:
网友评论