189. Rotate Array的问题?
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
nums = temp;
替换一个局部变量的引用没什么卵用哦@CRIMX 已经说的很明白了,就不赘述了,附上修改好的代码