LeetCode 283.Move Zeroes

LeetCode 283.Move Zeroes

Description:

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.

分析:

这道题很简单,可以利用vector标准库中的erase和push_back函数即可解决。
首先,定义cnt为0,用来标记已经循环遍历的个数,因为我们不断push_back,vector的长度其实是不变的,所以用cnt来判断是否退出循环。
然后,循环遍历vector,当遇到数为0的情况时,用erase函数将其删除,然后用push_back函数在末尾加上0即可。
这里要注意的是erase函数,因为iterator erase (const_iterator position);,说明vector.erase()接收一个迭代器的参数,然后返回值依然是迭代器,所以要按代码那样写,才能避免出现野指针的问题。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int cnt = 0;
for (vector<int>::iterator iter = nums.begin(); cnt != nums.size() && iter != nums.end();) {
if (*iter == 0) {
iter = nums.erase(iter);
nums.push_back(0);
}
else {
iter++;
}
cnt++;
}
}
};
int main() {
Solution s;
vector<int> nums;
int n;
cin >> n;
int t;
for (int i = 0; i < n; i++) {
cin >> t;
nums.push_back(t);
}
s.moveZeroes(nums);
for (int i = 0; i < n; i++) {
cout << nums[i] << " ";
}
return 0;
}
------本文结束感谢阅读------