示例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:巴黎铁塔反转反转再反转
class Solution { public void rotate(int[] nums, int k) { int length=nums.length; k%=length; reverse(nums,0,length-1-k);//先将数组全反转 reverse(nums,length-k,length-1);//反转头k个 reverse(nums,0,length-1);//反转k后面 } public void reverse(int[] nums,int start,int end){ while(start<end){ int temp=nums[start]; nums[start++]=nums[end]; nums[end--]=temp; } } }