189. 数组循环右移K位

it2022-05-08  17

题目链接:

https://leetcode-cn.com/problems/rotate-array/submissions/

 

解题思路:

这个方法基于这个事实:当我们旋转数组 k 次, k\%nk%n 个尾部元素会被移动到头部,剩下的元素会被向后移动。

在这个方法中,我们首先将所有元素反转。然后反转前 k 个元素,再反转后面 n-kn−k 个元素,就能得到想要的结果。

假设 n=7n=7 且 k=3k=3 。

原始数组 : 1 2 3 4 5 6 7反转所有数字后 : 7 6 5 4 3 2 1反转前 k 个数字后 : 5 6 7 4 3 2 1反转后 n-k 个数字后 : 5 6 7 1 2 3 4 --> 结果

1 class Solution { 2 public void rotate(int[] nums, int k) { 3 k = k %nums.length; 4 reverse(nums,0,nums.length-1); 5 reverse(nums,0,k-1); 6 reverse(nums,k,nums.length-1); 7 } 8 public void reverse(int []nums,int start,int end) 9 { 10 int temp; 11 while(start<end) 12 { 13 temp = nums[start]; 14 nums[start]=nums[end]; 15 nums[end]=temp; 16 start++; 17 end--; 18 } 19 } 20 }

 

转载于:https://www.cnblogs.com/wangyufeiaichiyu/p/11245122.html

相关资源:解决C语言数组元素循环右移的问题

最新回复(0)