summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/array/08_move_zeroes.cc
diff options
context:
space:
mode:
Diffstat (limited to 'top-interview-questions/easy/array/08_move_zeroes.cc')
-rw-r--r--top-interview-questions/easy/array/08_move_zeroes.cc23
1 files changed, 23 insertions, 0 deletions
diff --git a/top-interview-questions/easy/array/08_move_zeroes.cc b/top-interview-questions/easy/array/08_move_zeroes.cc
new file mode 100644
index 0000000..074944c
--- /dev/null
+++ b/top-interview-questions/easy/array/08_move_zeroes.cc
@@ -0,0 +1,23 @@
1class Solution {
2public:
3 void moveZeroes(vector<int>& nums) {
4 // Invariant: left subset of array satisfies requirement.
5 bool sorted = false;
6 for (size_t i = 0; (i < nums.size()) && !sorted; ++i) {
7 if (nums[i] == 0) {
8 // Look for j>i with which to swap this 0.
9 // If not found, then we're done.
10 bool found = false;
11 for (size_t j = i+1; j < nums.size(); ++j) {
12 if (nums[j] != 0) {
13 nums[i] = nums[j];
14 nums[j] = 0;
15 found = true;
16 break;
17 }
18 }
19 sorted = !found;
20 }
21 }
22 }
23};