https://leetcode.cn/problems/rotate-array/
题目要求
给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
遍历
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
Deque<Integer> queue = new ArrayDeque<>();
for (int i = n - k; i < n; i++) {
queue.offer(nums[i]);
}
for (int i = 0; i < n - k; i++) {
queue.offer(nums[i]);
}
for (int i = 0; i < n && !queue.isEmpty(); i++) {
nums[i] = queue.poll();
}
}
}
- 使用队列保存数组轮转后的元素,然后重新赋值
递归
class Solution {
private void reverse(int[] nums, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
reverse(nums, 0, n - k - 1);
reverse(nums, n - k, n - 1);
reverse(nums, 0, n - 1);
}
}
- 反转前n-k个区间,反转n-k到结尾的区间,反转整个数组;