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.
[show hint]
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
import java.util.Arrays;
class Solution {
public static void rotate(int[] nums, int k) {
int[] temp = Arrays.copyOf(nums, nums.length);
if (nums.length >= k) {
for (int i = 0; i < nums.length; i++) {
if (i + k > nums.length - 1) {
temp[i + k - nums.length] = nums[i];
} else {
temp[i + k] = nums[i];
}
}
}
nums = temp;
print(nums);
}
private static void print(int[] nums) {
for (int i : nums) {
System.out.print(i);
}
}
public static void main(String[] args) {
int[] nums = { 1, 2 };
rotate(nums, 1);
}
}
leetcode提交显示:
Input:
[1,2]
1
Output:
[1,2]
Expected:
[2,1]
nums = temp;
替换一个局部变量的引用没什么卵用哦