旋转数组

189. 轮转数组

给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。

示例 1:

1
2
3
4
5
6
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]

示例 2:

1
2
3
4
5
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]

提示:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

进阶:

  • 尽可能想出更多的解决方案,至少有 三种 不同的方法可以解决这个问题。
  • 你可以使用空间复杂度为 O(1)原地 算法解决这个问题吗?
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] newArr = new int[len];
for(int i = 0; i < len; i++){
newArr[( i + k ) % len] = nums[i];
}
//错误写法,copyOf是复制新的地址给形参nums
// nums = Arrays.copyOf(newArr, len);
//arraycopy是在目标数组上原地复制
System.arraycopy(newArr, 0, nums, 0, len);
}
}
  • 时间复杂度: O(n),其中 n为数组的长度
  • 空间复杂度: O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
if(k == 0) return;
reverse(nums, 0, nums.length-1);
reverse(nums, 0, k-1);
reverse(nums, k, nums.length-1);
}
public void reverse(int[] nums, int l, int r){
while(l < r){
int temp = nums[l];
nums[l++] = nums[r];
nums[r--] = temp;
}
}
}

时间复杂度:O(n),其中 n 为数组的长度。每个元素被翻转两次,一共 n 个元素,因此总时间复杂度为 O(2n)=O(n)

空间复杂度:O(1)


旋转数组
http://example.com/2023/02/16/算法/数组/7. 旋转数组/
作者
PALE13
发布于
2023年2月16日
许可协议