189 Rotate Array 旋轉(zhuǎn)數(shù)組
Description:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example:
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
題目描述:
給定一個(gè)數(shù)組,將數(shù)組中的元素向右移動(dòng) k 個(gè)位置,其中 k 是非負(fù)數(shù)。
示例:
示例 1:
輸入: [1,2,3,4,5,6,7] 和 k = 3
輸出: [5,6,7,1,2,3,4]
解釋:
向右旋轉(zhuǎn) 1 步: [7,1,2,3,4,5,6]
向右旋轉(zhuǎn) 2 步: [6,7,1,2,3,4,5]
向右旋轉(zhuǎn) 3 步: [5,6,7,1,2,3,4]
示例 2:
輸入: [-1,-100,3,99] 和 k = 2
輸出: [3,99,-1,-100]
解釋:
向右旋轉(zhuǎn) 1 步: [99,-1,-100,3]
向右旋轉(zhuǎn) 2 步: [3,99,-1,-100]
說(shuō)明:
盡可能想出更多的解決方案,至少有三種不同的方法可以解決這個(gè)問(wèn)題。
要求使用空間復(fù)雜度為 O(1) 的原地算法。
思路:
- 先將數(shù)組反轉(zhuǎn), 然后分別將[0, k) 和 [k, nums.size())部分反轉(zhuǎn)
- 每次取出最后一個(gè)元素放到第一個(gè)元素的位置
- 遞歸交換
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
void rotate(vector<int>& nums, int k)
{
int len = nums.size();
k %= len;
reverse(nums, 0, len - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, len - 1);
}
private:
void reverse(vector<int>& nums, int start, int end)
{
while (start < end) swap(nums[start++], nums[end--]);
}
};
Java:
class Solution {
public void rotate(int[] nums, int k) {
recursiveSwap(nums, k, 0, nums.length);
}
private void recursiveSwap(int[] nums, int k, int start, int length) {
k %= length;
if (k != 0) {
for (int i = 0; i < k; i++) swap(nums, start + i, nums.length - k + i);
recursiveSwap(nums, k, start + k, length - k);
}
}
private void swap(int[] nums, int i, int j) {
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
}
Python:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(k):
num = nums.pop()
nums.insert(0, num)