Java [Leetcode 189]Rotate Array

时间:2023-03-09 01:25:24
Java [Leetcode 189]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.

解题思路:

牺牲空间复杂度的话可以考虑开辟新的数组空间,然后依次移动即可;

本方法只用一个临时变量存放临时数据,然后依次的交换数据,如图所示:

Java [Leetcode 189]Rotate Array

Java [Leetcode 189]Rotate Array

但是注意会陷入局部循环的局面,这时将相应的下标后移一位。

public class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
if(length == 0)
return;
k = k % length;
int head = 0, curIndex = 0, nextIndex;
int curValue = nums[0], nextValue;
for(int i = 0; i < length; i++){
if(curIndex == head && i > 0){ //finish a circle,move to another circle
curIndex++;
head++;
curValue = nums[curIndex];
}
nextIndex = (curIndex + k) % length;
nextValue = nums[nextIndex];
nums[nextIndex] = curValue;
curIndex = nextIndex;
curValue = nextValue;
}
}
}

  

代码如下: