题目:
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.
解释:
注意不能使用额外空间哦
python代码:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i=0
_len=len(nums)
numnot0=_len-nums.count(0)
while i<numnot0:
if nums[i]==0:
nums.pop(i)
nums.append(0)
else:
i+=1
c++代码:
#include<algorithm>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int _len=nums.size();
int notzero_count=_len-count(nums.begin(),nums.end(),0);
int i=0;
while(i<notzero_count)
{
if (nums[i]==0)
{
nums.erase(nums.begin()+i);
nums.push_back(0);
}
else
i++;
}
}
};
结果:
学会使用<vector>
的erase()
函数。