https://leetcode-cn.com/problems/rotate-array
一 题目
给你一个数组,将数组中的元素向右轮转 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]
二 题解
class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
if(k%length==0){
return;
}
int[] arrays = Arrays.copyOf(nums,length);
int tagSource = 0;
int tag = tagSource+k;
while (tagSource<length){
tag = (tagSource + k)%length;
nums[tag] = arrays[tagSource];
tagSource++;
}
}
}
三 题解-翻转数组
* 时间复杂度:O(n) * 空间复杂度:O(1)
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start++] = nums[end];
nums[end--] = temp;
}
}
}
假设数组:[1,2,3,4,5,6,7,8,9]
k = 3, 结果应该为:[7,8,9,1,2,3,4,5,6]
翻转数组解法:
reverse(nums,0,8)—->[9,8,7,6,5,4,3,2,1]
reverse(nums,0,2)—->[7,8,9,6,5,4,3,2,1]
reverse(nums,3,8)—->[7,8,9,1,2,3,4,5,6]
解题的原理:选取数组后(k%n)长度的部分,作为一个整体,另外一部分作为一个整体
[1,2,3,4,5,6,7,8,9] k=3时,分为的两部分:[1,2,3,4,5,6][7,8,9]
然后将两部分交换顺序:[7,8,9][1,2,3,4,5,6],这就是需要的结果。
只不过翻转数组是将整个数组翻转后,然后按块来进行翻转:
[1,2,3,4,5,6,7,8,9] 翻转后:[9,8,7,6,5,4,3,2,1]
然后分成两个部分:[9,8,7][6,5,4,3,2,1]
然后分别翻转:[7,8,9][1,2,3,4,5,6]