Move Zeroes 539
Question
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.
Notice
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Example
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Solution
双指针法two pointers。第一个指针遇到0就停下(在0之前的位置),第二个指针继续寻找之后第一个非0的元素,找到之后和第一个指针后面的0交换,第一个指针移动一位。即第一个指针和第二个指针之间的元素为0。
代码如下:
public class Solution {
/**
* @param nums an integer array
* @return nothing, do this in-place
*/
public void moveZeroes(int[] nums) {
// Write your code here
if(nums == null || nums.length == 0){
return;
}
int i = -1;;
for(int j = 0; j < nums.length; j++){
if(nums[j] != 0){
i++;
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}