题目链接
题目内容
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
解题思路
1.设置两个指针,都指向数组的第0个位置;
2.右指针每次向右移动一位,遇到非0则与左指针的数指进行交换,如果数组的nums[0]为非0,第一次是不会有交换的。
代码
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size(), left = 0, right = 0;
while (right < n) {
if (nums[right]) {
swap(nums[left], nums[right]);
left++;
}
right++;
}
}
};