題目:
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.
思路與步驟:
思路1:
用一個 List 存儲變換好順序的數組,然後賦值給原數組;
思路2:
用一個長度爲 k 的數組存儲變換好的數組的前半截,後半截直接在原數組上修改;
思路3:
寫一個 reverse() 函數,然後用三步逆轉實現。
編程實現:
Solution-1:
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return;
k = k % len;
List<Integer> numlist = new ArrayList<Integer>();
for(int i=0; i<k; i++) numlist.add(nums[nums.length-k+i]);
for(int i=k; i<nums.length; i++) numlist.add(nums[i-k]);
for(int i=0; i<nums.length; i++) nums[i] = numlist.get(i);
}
}
Solution-2:
public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length <= 1) return;
int step = k % nums.length;
int[] tmp = new int[step];
for(int i=0; i<step; i++) tmp[i] = nums[nums.length - step + i];
for(int i=nums.length-step-1; i>= 0; i--) nums[i + step] = nums[i];
for(int i=0; i<step; i++) nums[i] = tmp[i];
}
}
Solution-3:
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return;
k = k % len;
reverse(nums, 0, len-1);
reverse(nums, 0, k-1);
reverse(nums, k, len-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--;
}
}
}