Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to[5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
题意:旋转数组,给定数组长度n,k表示从右向左数k个数,将这k个数旋转到数组前面
分类:数组
解法1:三次反转数组即可。首先反转0到n-k-1,再反转n-k到n-1,最后将整个数组反转
public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length==k) return;//k等于数组长度,直接返回
if(nums.length<k) k = k%nums.length;//k大于数组长度,取k%nums.length
rotate(nums, 0, nums.length-1-k);
rotate(nums, nums.length-k, nums.length-1);
rotate(nums, 0, nums.length-1);
}
public void rotate(int[] nums,int i,int j){
while(i<j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
i++;j--;
}
}
}