问题:https://leetcode.com/problems/move-zeroes/
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,则跟第一个0所在的位置进行交换。
代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int l=nums.size();
for(int num1=0,num2=0;num2<l;num2++){
if(nums[num2]!=0)
swap(nums[num1++],nums[num2]);
}
}
};