-
Notifications
You must be signed in to change notification settings - Fork 0
/
283-移动零.cpp
47 lines (42 loc) · 904 Bytes
/
283-移动零.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
// @before-stub-for-debug-begin
// @before-stub-for-debug-end
/*
* @lc app=leetcode.cn id=283 lang=cpp
*
* [283] 移动零
*/
// @lc code=start
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
void moveZeroes(vector<int>& nums)
{
const int size = nums.size();
int k = 0; // k指向第一个未排好的元素
for (int i = 0; i < size; i++) {
if (nums[i]) {
if (i != k)
swap(nums[i], nums[k++]);
else
k++;
}
}
}
};
// @lc code=end
int main()
{
vector<int> nums = {1, 0, 1, 0, 0, 3, 0, 4};
Solution().moveZeroes(nums);
for (auto i : nums) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
cout << endl;
return 0;
}