题目来源:力扣
法一:
class Solution {
public void rotate(int[] nums, int k) {
for(int times = 0; times < k; times++){
int lastNumCopy = nums[nums.length - 1];
for(int i = nums.length - 1; i > 0; i--){
nums[i] = nums[i - 1];
}
nums[0] = lastNumCopy;
}
}
}
用时:138ms
法二
class Solution {
public void rotate(int[] nums, int k) {
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);
}
}
}
用时:0ms
法三:
lass Solution {
public void rotate(int[] nums, int k) {
if (nums.length == 1 || k == nums.length) {
return;
}
if (k > nums.length) {
k = k - nums.length;
}
int[] result = new int[nums.length];
for (int i = nums.length - k, j = 0; i < nums.length; i++, j++) {
result[j] = nums[i];
}
for (int i = 0, j = k; i < nums.length - k && j < result.length; i++, j++) {
result[j] = nums[i];
}
System.arraycopy(result, 0, nums, 0, nums.length);
}
}
用时:2ms