notes/OJ notes/pages/Leetcode Move-Zeroes.md

89 lines
1.5 KiB
Markdown
Raw Permalink Normal View History

2022-07-11 10:03:24 +08:00
# Leetcode Move-Zeroes
#### 2022-07-11 09:55
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
> #algorithm #two_pointers #array_in_place_operation
>
2022-07-11 10:03:24 +08:00
> ##### Data structures:
2022-09-03 15:41:36 +08:00
>
> #DS #array
>
2022-07-11 10:03:24 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-09-06 20:22:48 +08:00
> #coding_problem #difficulty_easy
2022-09-03 15:41:36 +08:00
>
2022-07-11 10:03:24 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode
>
2022-07-11 10:03:24 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-11 10:03:24 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-11 10:03:24 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-11 10:03:24 +08:00
- [Link to problem](https://leetcode.com/problems/move-zeroes/)
2022-09-03 15:41:36 +08:00
---
2022-07-11 10:03:24 +08:00
### 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:**
2022-09-03 15:41:36 +08:00
- `1 <= nums.length <= 104`
- `-231 <= nums[i] <= 231 - 1`
2022-07-11 10:03:24 +08:00
### Thoughts
> [!summary]
2022-09-03 15:41:36 +08:00
> This is a #array_in_place_operation problem.
2022-07-11 10:03:24 +08:00
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<int> &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;
}
}
};
2022-09-03 15:41:36 +08:00
```