From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- .../easy/array/08_move_zeroes.cc | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 top-interview-questions/easy/array/08_move_zeroes.cc (limited to 'top-interview-questions/easy/array/08_move_zeroes.cc') 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 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + // Invariant: left subset of array satisfies requirement. + bool sorted = false; + for (size_t i = 0; (i < nums.size()) && !sorted; ++i) { + if (nums[i] == 0) { + // Look for j>i with which to swap this 0. + // If not found, then we're done. + bool found = false; + for (size_t j = i+1; j < nums.size(); ++j) { + if (nums[j] != 0) { + nums[i] = nums[j]; + nums[j] = 0; + found = true; + break; + } + } + sorted = !found; + } + } + } +}; -- cgit v1.2.3