189. Rotate Array - LeetCode

189. Rotate Array

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?

Solution:

不断往新数组中添加元素, 该元素的索引通过求余数得到

// Time:O(n), Space:O(n);
class Solution {
public:
void rotate(vector<int>& nums, int k) {
vector<int> v;
int n = nums.size();
for (int i = k; i < n + k; i++) {
v.push_back(nums[i % n]);
}
nums = v;
// return v;
}
};

扫描k遍, 每一遍都将首个元素移到最后

// ERROR:
// Time:O(n^2), Space:O(1);
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
for (int i = 0; i < k; i++) {
for (int j = 0; j < n-1; j++) {
int tmp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = tmp;
}
}
}
}; // 从左往右写反

扫描k遍, 每遍都将最后一个元素移动最前

// Time:O(n^2), Space:O(1);
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
for (int i = 0; i < k; i++) {
for (int j = n-1; j > 0; j--) {
int tmp = nums[j]; nums[j] = nums[j-1]; nums[j-1] = tmp;
}
}
}
}; // 改成从右往左
// 但是Time Limit Exceeded

最新的解法,

0 1 2 3 4
3 4 0 1 3

观察数组构造, 将3通过交换到最首位, 4位于其次

// Time:   Space:O(n)
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.size() == 0 || k == 0 || k % nums.size() ==0)
return;
int n = nums.size(), m = k % n;

for (int i = n-m; i <= n-1; i++) {
for (int j = i; j > i-(n-m); j--) {
int tmp = nums[j]; nums[j] = nums[j-1]; nums[j-1] = tmp;
}
}
}
}; // 改成从右往左, 添加数组为空, k为零的情况, 求余也为0的情况