forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main4.cpp
42 lines (33 loc) · 881 Bytes
/
main4.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
/// Source : https://leetcode.com/problems/move-zeroes/description/
/// Author : liuyubobobo
/// Time : 2017-02-09
#include <iostream>
#include <vector>
using namespace std;
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0; // keep nums[0...k) are all zero elements
for(int i = 0 ; i < nums.size() ; i ++ )
if(nums[i])
// avoid self swapping
if(k != i)
swap(nums[k++], nums[i]);
else
k ++;
}
};
void printVec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
int arr[] = {0, 1, 0, 3, 12};
vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
Solution().moveZeroes(vec);
printVec(vec);
return 0;
}