标签:
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
解题思路:
几天没回来刷题结果Leetcode又出新题了。。真的是刷不完的节奏了吗。。。
我的思路是copy给的array两遍, 比如{1, 2, 3, 4, 5, 6, 7}就变成了{1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7} (跟亚麻他们家OA的那道right rotation差不多思路)
然后找到k该开始的那个点, 比如 k = 3, 就是从index = nums.length - k开始的~从那开始往后截取就行啦~~~
注意的是: k有可能是nums长度的各种各种倍, 比如100多倍这样子, 所以要取余~
1 public void rotate(int[] nums, int k) { 2 k = k % nums.length; 3 int[] temp = new int[nums.length * 2]; 4 for(int i = 0; i < nums.length; i++){ 5 temp[i] = nums[i]; 6 temp[i + nums.length] = nums[i]; 7 } 8 int res = nums.length - k; 9 for(int i = 0; i < nums.length; i++){ 10 nums[i] = temp[res]; 11 res++; 12 } 13 }
标签:
原文地址:http://www.cnblogs.com/sherry900105/p/4299110.html