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.
反正我是自己没理解这个题目,后来根据提交出错的信息猜测,他里边的k是能大于数组长度的,而且与数组长度的关系是k对数组长度取余数得到的数字为真正的转的那个数
public class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length;
k%=n;
int j=n-k;
int[] a=new int[n];
for(int i=j;i<n;i++)
a[i-j]=nums[i];
for(int i=0;i<n-k;i++)
a[k+i]=nums[i];
for(int i=0;i<n;i++)
nums[i]=a[i];
}
}
这一个是用自带的copy数组的函数来进行实现的
public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] temp = new int[len];
k%=len;
System.arraycopy(nums, 0, temp, k, len-k);
System.arraycopy(nums, len-k, temp, 0, k);
System.arraycopy(temp, 0, nums, 0, len);
}
}
还有一种比较巧妙的方法,先吧[1,2,3,4,5,6,7]反转前半部分即为[4,3,2,1,5,6,7],再反转后半部分[4,3,2,1,7,6,5],再整个的反转,即可以得到[5,6,7,1,2,3,4],代码就不写了
本文介绍如何使用多种方法将数组元素向右旋转指定位数。包括利用数组复制、取余运算简化k值和整体反转数组等技巧,旨在提供灵活多样的解决方案。

618

被折叠的 条评论
为什么被折叠?



