From ef7392deb70362ac644168e1ae1c565e06d0ae7f Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 11 Jul 2022 10:03:24 +0800 Subject: [PATCH] vault backup: 2022-07-11 10:03:24 --- OJ notes/pages/Leetcode Move-Zeroes.md | 87 ++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 OJ notes/pages/Leetcode Move-Zeroes.md diff --git a/OJ notes/pages/Leetcode Move-Zeroes.md b/OJ notes/pages/Leetcode Move-Zeroes.md new file mode 100644 index 0000000..d3a65cc --- /dev/null +++ b/OJ notes/pages/Leetcode Move-Zeroes.md @@ -0,0 +1,87 @@ +# Leetcode Move-Zeroes + +#### 2022-07-11 09:55 + +> ##### Algorithms: +> #algorithm #two_pointers #array_in_place_operation +> ##### Data structures: +> #DS #array +> ##### Difficulty: +> #coding_problem #difficulty-easy +> ##### Additional tags: +> #leetcode +> ##### Revisions: +> N/A + +##### Related topics: +```expander +tag:#array_in_place_operation OR tag:#two_pointers +``` + +- [[Leetcode Intersection-of-Two-Arrays-II]] +- [[Leetcode Merge-Sorted-Array]] +- [[Leetcode Merge-Two-Sorted-Lists]] +- [[Leetcode Rotate-Array]] +- [[Leetcode Squares-of-a-Sorted-Array]] +- [[Two pointers approach]] + + +##### Links: +- [Link to problem](https://leetcode.com/problems/move-zeroes/) +___ +### Problem + +Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. + +**Note** that you must do this in-place without making a copy of the array. + +**Follow up:** Could you minimize the total number of operations done? + +#### Examples + +**Example 1:** + +**Input:** nums = [0,1,0,3,12] +**Output:** [1,3,12,0,0] + +**Example 2:** + +**Input:** nums = [0] +**Output:** [0] + +#### Constraints + +**Constraints:** + +- `1 <= nums.length <= 104` +- `-231 <= nums[i] <= 231 - 1` + +### Thoughts + +> [!summary] +> This is a #array_in_place_operation problem. + +Because the data can be overwritten, and zeros can be predicted in the result array, I use in-place array operations. + +### Solution + +```cpp +class Solution { +public: + void moveZeroes(vector &nums) { + // Tow pointers, since data can be overwritten and one pointer is faster + // than another. + int num = 0; + + for (int i = 0; i < nums.size(); i++) { + if (nums[i] != 0) { + nums[num++] = nums[i]; + } + } + + for (int j = num; j < nums.size(); j++) { + nums[j] = 0; + } + } +}; +``` \ No newline at end of file