题目链接:https://leetcode.com/problems/move-zeroes/
题面:
283. Move Zeroes
Easy
208477FavoriteShare
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.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
题意:将非0数按顺序前移,不改变相对顺序。
解题:
用队列保存可放的0的位置,遇到非0数,逐个前移,注意前移后,当前位变0,且变成一个可放置的位置。
代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
queue <int> pos;
for(int i=0;i<nums.size();i++){
if(nums[i]==0){
pos.push(i);
}
else{
if(pos.size()==0)
continue;
else{
int p=pos.front();
pos.pop();
nums[p]=nums[i];
nums[i]=0;
pos.push(i);
}
}
}
}
};