目录
问题描述
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
- 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?
给一个数组,向右移动转动K步,K不是负数。
扩展:
- 尽可能提出解决方法,至少有三种方法。
- 你能以时间复杂度O(1)来解决它么?(英语渣,这句不知道如何翻译)
举例说明
Example 1:
Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]
限制
Constraints:
1 <= nums.length <= 2 * 10^4
- It's guaranteed that
nums[i]
fits in a 32 bit-signed integer.k >= 0
1 <= nums.length <= 2 * 10^4
- 保证nums[i]是32位有符号整数。
k >= 0
实现
Runtime:16ms
例子1:Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]。我首先让第一个,索引为0的元素到达转动3步的位置,即索引3。交换nums[0]和nums[3],数组就变成了nums = [4,2,3,1,5,6,7]。但是问题就是,原先索引是3的元素4距离它的目的地——索引为6的元素7更远了。远了多少距离?2k。当把4送到7的位置,元素7距离它的目的地的距离是3k,以此类推。
0+3=3 i+1*k
【4 2 3 1 5 6 7】
0+6=6 i+2*k
【7 2 3 1 5 6 4】
0+9-7=2 i+3*k
【3 2 7 1 5 6 4】
0+12-7=5 i+4*k
【6 2 7 1 5 3 4】
0+15-7-7=1 i+5*k
【2 6 7 1 5 3 4】
0+18 -7-7=4 i+6*k
【5 6 7 1 2 3 4】
i+n*k n∈[1,n) 可能会大于numsSize,此时需要减小到[0,numsSize)。得到的数字就是索引为0的元素需要到达的索引。综上,进行(数组长度-1)次操作即可达到目的。然而也有例外。
例子2:Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100]。我们继续用上面的方法尝试解决这个例子。
0+2=2 i+1*k
【3,-100,-1,99】
4-4 i+2*k <<<<<这里得到的数字是0,从output可以看出,-1和3交换已到达双方的目的地。
【3,-100,-1,99】
1+2 i+1*k <<<<<索引往前加1,此时元素99距离目的地依然是1*k
【3,99,-1,-100】
正好又是3(数组长度为4)步换完所有元素。综上,我们需要判断得出的目的地索引是否是原索引,如果是,则说明该元素已经到达了目的地;如果不是,则要将元素移动到目的地。
void rotate(int* nums, int numsSize, int k) {
int i, count, change, j;
for (i = 0, count = 1, j = 1; count < numsSize; count++, j++) {
change = nums[i];
if (i + j * k - (i + j * k) / numsSize*numsSize == i) {
i++;
j = 0;
continue;
}
nums[i] = nums[i + j * k - (i + j * k) / numsSize * numsSize];
nums[i + j * k - (i + j * k) / numsSize * numsSize] = change;
}
}
Runtime:4ms
void rotate(int* nums, int numsSize, int k){
int arr[numsSize];
for (int i = 0; i < numsSize; i++ ){
arr[(i+k) % numsSize] = nums[i];
}
for (int i=0 ; i < numsSize; i++){
nums[i] = arr[i];
}
}