【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
189. Rotate Array(相当于循环右移k位)
Given an array, rotate the array to the right by k steps, where k is non-negative.
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?
相关题目:循环左移
//方法一:使用额外的数组,索引i用i+k替换,然后把组织好的数组复制过去
// O(n), O(n)
/*class Solution
{
public:
void rotate(vector<int>& a, int k)
{
vector<int> temp(a);
int n = a.size();
for(int i = 0; i<n; i++)
{
temp[(i+k)%n] = a[i]; //进行题意的rotated
}
a = temp; //将数据复制过去
}
};*/
/*
方法二:多次反转法
Original List : 1 2 3 4 5 6 7
After reversing all numbers : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result
分析:O(n) O(1)
*/
#include <algorithm>
class Solution
{
public:
void rotate(vector<int>& a, int k)
{
k %= a.size(); //以免k过大
reverse(a.begin(), a.end()); //反转所有元素
reverse(a.begin(), a.begin()+k); //反转前k个元素
reverse(a.begin()+k, a.end()); //反转剩余元素(注意reverse反转区间为前闭后开,故这里为a.begin()+k)
}
};
//方法三:使用循环替代,略