方法1:模拟操作过程
class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length;
k=k%n;
for(int i=0;i<k;i++){
int temp=nums[n-1];
move(nums,0);
nums[0]=temp;
}
}
public void move(int[] nums,int a){
for(int i=nums.length-2;i>=a;i--){
nums[i+1]=nums[i];
}
}
}
方法2:翻转整体,再翻转前k个,再翻转后面的
class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length-1;
k=k%(n+1);//不要忘写
reverse(nums,0,n);
reverse(nums,0,k-1);
reverse(nums,k,n);
}
public void reverse(int[] nums,int a,int b){
int low=a;
int high=b;
while(low<high){
int temp=nums[high];
nums[high]=nums[low];
nums[low]=temp;
low++;
high--;
}
}
}