题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的代码
class Solution {
public void moveZeroes(int[] nums) {
int head = 0;
int tail = 1;
// head find zero and tail find nonzero
while(tail < nums.length) {
while(nums[head] != 0) {
head ++;
tail ++;
if (tail == nums.length){return;}
}
while(nums[tail] == 0) {
tail++;
if (tail == nums.length){return;}
}
nums[head] = nums[tail];
nums[tail] = 0;
}
}
}
小结
传统的双指针思路,注意数组越界问题即可。