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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
典型的双指针题目,找到0,交换,总共就两件事,可以一边找一边换,检索完就做完,也可以找完统一归0,复杂度没什么本质差别。
代码一:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int i = 0, j = 0;
while (j < n) {
if (nums[j] != 0) {
swap(nums[i], nums[j]);
i++;
j++;
}
else
j++;
}
}
代码二:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int i = 0, j = 0;
for (; j < n; j++) {
if (nums[j] != 0) {
nums[i++] = nums[j];
}
}
for (; i < n; i++) {
nums[i] = 0;
}
}