vault backup: 2022-07-10 10:22:17

This commit is contained in:
juan 2022-07-10 10:22:17 +08:00
parent 76faef22ff
commit 95cd8fd7b8

View file

@ -3,19 +3,19 @@
#### 2022-07-10 08:54 #### 2022-07-10 08:54
> ##### Algorithms: > ##### Algorithms:
> #algorithm #array_in_place_operation > #algorithm #array_in_place_operation #reverse_array
> ##### Data structures: > ##### Data structures:
> #DS #array > #DS #array
> ##### Difficulty: > ##### Difficulty:
> #coding_problem #difficulty-medium > #coding_problem #difficulty-medium
> ##### Additional tags: > ##### Additional tags:
> #leetcode > #leetcode #CS_list_need_practicing #CS_list_need_understanding
> ##### Revisions: > ##### Revisions:
> N/A > N/A
##### Related topics: ##### Related topics:
```expander ```expander
tag:#array_in_place_operation tag:#array_in_place_operation OR #reverse_array
``` ```
@ -56,16 +56,49 @@ rotate 2 steps to the right: [3,99,-1,-100]
#### Method 1: Array In-place operation #### Method 1: Array In-place operation
This one is hard.
==#TODO: Revisit this one some other day==
- Reversing a subarray doesn't change the continuity, the neighbors inside the subarray is same.
- Reversing a subarray changes the edge's neighbors
Suppose a array looks like:
```
[1, 2,| 3, 4, 5]
```
If reverse all two subarrays, the neighbors isn't changed
only the orders are changed
```
[1, 2,| 3, 4, 5]: 5-1-2, 1-2-3, 2-3-4, 4-5-1
[2, 1,| 5, 4, 3]: 3-2-1, 2-1-5, 5-1-4, 4-3-2
```
When reversed back, the order is changed back to original, but the two sub-arrays are swapped
```
[3, 4, 5,| 1, 2]
```
By doing this, the order in inner-array isn't changed, but the order of all is changed.
#### Method 2: Copy #### Method 2: Copy
Watch out for integer overflow. Watch out for integer overflow.
#### Method 3: CPP's STL #### Method 3: CPP's STL sway subarrays
Remember to sanitize k, when k > size
### Solution ### Solution
Method 1:
```cpp
```
Method 2: Method 2:
```cpp ```cpp
class Solution { class Solution {
@ -96,3 +129,31 @@ public:
} }
}; };
``` ```
Method 3:
```cpp
class Solution {
void swap(vector<int> &nums, int l, int r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
public:
void rotate(vector<int> &nums, int k) {
int size = nums.size();
if (size <= 1) {
return;
}
// STL
k = k % size;
k = size - k;
while (k < 0) {
k += size;
}
nums.insert(nums.end(), nums.begin(), nums.begin() + k);
nums.erase(nums.begin(), nums.begin() + k);
}
};
```