题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
思路
遍历数组,用一个指针j记录上一次交换中的下标小的位置的下一个位置。找到不为0的就与该指针交换位置。目的是把非零的数按顺序往前移动(移动到0的前面)。
代码
class Solution {
public:void moveZeroes(vector<int>& nums) {int last = 0;for(int i=0;i<nums.size();i++) {if(nums[i]!=0) {swap(nums[i],nums[last]);last++;}}}
};