Easy 用时5分钟。
精简代码: version 1,未merge逻辑
public class Solution {
public void moveZeroes(int[] nums) {
int slow = 0;
int length = nums.length;
for (int i=0;i<length;i++){
if(nums[i] != 0){
if(nums[slow] != 0) slow ++;
else{
swap(slow, i, nums);
slow ++;
}
}
}
}
private void swap(int slow, int i, int[] nums){
int temp = nums[i];
nums[i] = nums[slow];
nums[slow] = temp;
}
}
Version2: merge if else
public class Solution {
public void moveZeroes(int[] nums) {
//8:38
int slow = 0;
int length = nums.length;
for (int i=0;i<length;i++){
if(nums[i] != 0){
if(nums[slow] == 0) swap(slow, i, nums);
slow ++;
}
}
}
private void swap(int slow, int i, int[] nums){
int temp = nums[i];
nums[i] = nums[slow];
nums[slow] = temp;
}
}