原題鏈接 https://leetcode.com/problems/rotate-array/
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
[1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
數組移位。
然而我並有想出o(1) 的額外空間,然後還不超時的情況。。
可以先將k對n取餘,因爲k完全可以比n大,表示數組移動了一圈,然而這一圈並不需要做。
如果k%n == 0 表示剛好移動很多圈,所以什麼事情都不用做。
如果k % n != 0 可以創建一個k大小的數組,然後將原數組後面k個元素放在臨時數組中。
然後開始移動原數組中開始的元素向後移動k位。
再將臨時數組中的元素放在原數組的前k個位置中去。
class Solution {
public:
void rotate(int nums[], int n, int k) {
k = k % n ;
if(k == 0)return;
int* tmp = new int[k];
for(int i = n - k; i < n; ++i)
tmp[i - n + k] = nums[i];
for(int i = n - 1; i >= k ; --i)
nums[i] = nums[i - k];
for(int i = 0; i < k; ++i)
nums[i] = tmp[i];
}
};