暴力法。这个方法我也想到了,就是实现了很长时间
public static void rotate(int[] nums, int k) {//114ms
int privious,temp;
for (int i = 0; i <k ; i++) {
privious = nums[nums.length-1];
for (int j = 0; j < nums.length; j++) {
temp = nums[j];
nums[j] = privious;
privious = temp;
}
}
for (int i = 0; i <nums.length ; i++) {
System.out.println(nums[i]);
}
}
使用额外数组,不过和题意不符合,也算是一个方法
public static void rotate(int[] nums, int k) {//1ms
int[] a = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
a[(i + k) % nums.length] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = a[i];
}
}
这个方法看了很长市价环形数组,的确牛逼
public static void rotate1(int[] nums, int k) {//1ms
k = k % nums.length;
int count = 0;
for (int start = 0; count < nums.length; start++) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % nums.length;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
使用反转
public static void rotate(int[] nums, int k) {//0ms
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
来源:CSDN
作者:ldd儆儆
链接:https://blog.csdn.net/qq_38304320/article/details/103489560