轮转数组
难度:
标签:
题目描述
给定一个整数数组 nums
,将数组中的元素向右轮转 k
个位置,其中 k
是非负数。
示例 1:
输入: 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:
输入: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)
的 原地 算法解决这个问题吗?
代码结果
运行时间: 28 ms, 内存: 23.4 MB
/*
* Problem: Given an array, rotate the array to the right by k steps, where k is non-negative.
* Example 1:
* Input: nums = [1,2,3,4,5,6,7], k = 3
* Output: [5,6,7,1,2,3,4]
* Example 2:
* Input: nums = [-1,-100,3,99], k = 2
* Output: [3,99,-1,-100]
*
* Approach using Java Streams:
* 1. Normalize k to ensure it is within the bounds of the array length.
* 2. Use streams to concatenate the two parts of the array that need to be swapped.
*/
import java.util.Arrays;
import java.util.stream.IntStream;
public class RotateArrayStream {
public int[] rotate(int[] nums, int k) {
int n = nums.length;
k = k % n;
return IntStream.concat(
Arrays.stream(Arrays.copyOfRange(nums, n - k, n)),
Arrays.stream(Arrays.copyOfRange(nums, 0, n - k))
).toArray();
}
}
解释
方法:
这个题解的思路是直接切片。首先将 k 对数组长度取模,得到实际需要轮转的次数。然后将原数组切片为两部分:后 k 个元素 nums[-k:] 和除去后 k 个元素的部分 nums[:-k],再将这两部分拼接起来赋值给原数组,即可得到轮转后的结果。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在题解中提到`k = k % len(nums)`的操作是为了什么?如果不进行这一步操作,会出现什么问题?
▷🦆
题解中提到使用切片来实现数组的轮转,这种方式在面对极大的数组时效率如何?是否存在更高效的方法?
▷🦆
题解中的方法是否能正确处理当`k`等于0或`k`等于数组长度的特殊情况?
▷