k指的是每个元素移动的数目,如果k大于数组长度,移动的则是k%nums.length
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
k = k%len;
int[] temp = new int[k];
// Save k elements from the end of the array
for(int i = 0; i < k; i++) {
temp[i] = nums[len-k+i];
}
// Shift all elements k positions to the right starting from the end of the array
for(int i = len-1; i > k-1; i--) {
nums[i] = nums[i-k];
}
// Copy those saved elements back to the front of the array
for(int i = 0; i < k; i++) {
nums[i] = temp[i];
}
}
}
k指的是每个元素移动的数目,如果k大于数组长度,移动的则是k%nums.length public class Solution { public void rotate(int[] nums, int k) { int len = nums.length; k = k%len; int[] temp = new int[k]; // Save k elements from the end of the array for(int i = 0; i < k; i++) { temp[i] = nums[len-k+i]; } // Shift all elements k positions to the right starting from the end of the array for(int i = len-1; i > k-1; i--) { nums[i] = nums[i-k]; } // Copy those saved elements back to the front of the array for(int i = 0; i < k; i++) { nums[i] = temp[i]; } } }