给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
题目来源:力扣(LeetCode)
采用双指针的解法
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
if(nums == null){
return;
}
//第一次遍历时,j指针记录非0的个数,只要非0的统统都赋给nums[j]
for(int i=0; i<nums.length; ++i){
if(nums[i] != 0){
nums[j++] = nums[i];
}
}
//非0元素统计完,剩下的都是0了,所以第二遍遍历将末尾的元素都赋为0即可
for(int i=j; i<nums.length; ++i){
nums[i] = 0;
}
}
}