- 直接开新数组,暴力遍历,新位置=(原位置+k)%nums.length
class Solution {
public void rotate(int[] nums, int k) {
int[] ans = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int pos = (i + k) % nums.length;
ans[pos] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = ans[i];
}
}
}
- 多轮元素轮转
还要想到 nums = {1,2,3,4}, k = 2的情况
class Solution {
public void rotate(int[] nums, int k) {
int start = 0, cnt = 0;
while (cnt < nums.length) {
int curPos = start;
int curNum = nums[curPos];
// 也可能 nums: 1 2 3 4, k = 2,直接跳回去的情况
do {
int nextPos = (curPos + k) % nums.length;
int temp = nums[nextPos];
nums[nextPos] = curNum;
curNum = temp;
curPos = nextPos;
cnt++;
}
while (curPos != start); // curPos != satrt说明直接在这循环一次搞定
start++;
}
}
}
- 三次翻转
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
int left = start, right = end;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}