原题链接:Move Zeros
思路分析:将元素0移动到数组末端并保持非0元素相对顺序不变,而且要in-place。
使用双指针,一个指针遍历,另一个指针始终保持指向数组前段非0元素的最后一个
遍历指针遍历完,将指向指针之后的元素都置0即可;
题解:
public class Solution {
public void moveZeroes(int[] nums) {
/*
Time Complexity:O(N)
Space Complexity:O(1)
*/
int i=-1;
for(int j=0;j<nums.length;j++){
if(nums[j]!=0){
i++;
nums[i]=nums[j];
}
}
i++;
while(i<nums.length){
nums[i]=0;
i++;
}
}
}