题目:
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]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
代码:
不知道为什么,在本地可以运行,提交上去显示 Submission Result: Runtime Error ,感觉可能是越界?不知道。。调不出来了。。(把0和后面非0的交换)
class Solution {
public:
vector<int> moveZeroes(vector<int>& nums) {
for(auto zero = nums.begin(); zero < nums.end(); zero++){
if ( *zero == 0 ){
auto notzero = zero;
for(notzero; notzero < nums.end(); notzero++){
if(*notzero != 0)
break;
}
if (zero != notzero)
iter_swap(zero, notzero);
}
}
return nums;
}
};
换个思路(把后面非0的元素和前面的0元素交换):
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int last = 0, cur = 0;
while(cur < nums.size()) {
if(nums[cur] != 0) {
swap(nums[last], nums[cur]);
last++;
}
cur++;
}
}
};
别人的代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nonzero = 0;
for(int n:nums) {
if(n != 0) {
nums[nonzero++] = n;
}
}
for(;nonzero<nums.size(); nonzero++) {
nums[nonzero] = 0;
}
}
};