From 76faef22ff29c3e7a8ce09cfb5713e46fa0c309f Mon Sep 17 00:00:00 2001 From: juan Date: Sun, 10 Jul 2022 09:57:15 +0800 Subject: [PATCH] vault backup: 2022-07-10 09:57:15 --- OJ notes/pages/Leetcode Rotate-Array.md | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/OJ notes/pages/Leetcode Rotate-Array.md b/OJ notes/pages/Leetcode Rotate-Array.md index 7a9ecfc..50a1207 100644 --- a/OJ notes/pages/Leetcode Rotate-Array.md +++ b/OJ notes/pages/Leetcode Rotate-Array.md @@ -58,6 +58,41 @@ rotate 2 steps to the right: [3,99,-1,-100] #### Method 2: Copy +Watch out for integer overflow. + #### Method 3: CPP's STL + + ### Solution + +Method 2: +```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; + } + // Copy + k = size - k; + while (k < 0) { + k += size; + } + vector ans(nums.size()); + for (int i = 0; i < size; i++) { + ans[i] = nums[(i + k) % size]; + } + for (int i = 0; i < size; i++) { + nums[i] = ans[i]; + } + } +}; +``` \ No newline at end of file