Question
Solution
题目大意:数组中最后一个元素移到第一个,称动k次
思路:用笨方法,再复制一个数组
Java实现:
public void rotate(int[] nums, int k) {
int[] numsCopy = Arrays.copyOf(nums, nums.length);
for (int i=0; i<nums.length; i++) {
nums[(i+k)%nums.length] = numsCopy[i];
}
}
别人的实现:
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}