From 95cd8fd7b8a0fd99ed588dbaaaac772a11a383e4 Mon Sep 17 00:00:00 2001 From: juan Date: Sun, 10 Jul 2022 10:22:17 +0800 Subject: [PATCH] vault backup: 2022-07-10 10:22:17 --- OJ notes/pages/Leetcode Rotate-Array.md | 71 +++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/OJ notes/pages/Leetcode Rotate-Array.md b/OJ notes/pages/Leetcode Rotate-Array.md index 50a1207..ff9f3a0 100644 --- a/OJ notes/pages/Leetcode Rotate-Array.md +++ b/OJ notes/pages/Leetcode Rotate-Array.md @@ -3,19 +3,19 @@ #### 2022-07-10 08:54 > ##### Algorithms: -> #algorithm #array_in_place_operation +> #algorithm #array_in_place_operation #reverse_array > ##### Data structures: > #DS #array > ##### Difficulty: > #coding_problem #difficulty-medium > ##### Additional tags: -> #leetcode +> #leetcode #CS_list_need_practicing #CS_list_need_understanding > ##### Revisions: > N/A ##### Related topics: ```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 +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 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 +Method 1: + +```cpp + +``` + Method 2: ```cpp class Solution { @@ -95,4 +128,32 @@ public: } } }; +``` + +Method 3: +```cpp +class Solution { + void swap(vector &nums, int l, int r) { + int temp = nums[l]; + nums[l] = nums[r]; + nums[r] = temp; + } + +public: + void rotate(vector &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); + } +}; ``` \ No newline at end of file