描述:
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]
Hint:Related problem: Reverse Words in a String II
思路:
當然,一個很簡單且容易想到的思路就是直接循環移位k位即可,但每次都要移動n個元素,即總共需要移動k*n個元素
和Reverse Words in a String II題目類似,還有一種通過改變固定數目的元素就可以實現移位數組的功能,即先將1~len-k,len-k~len之間的元素逆置,最後將1~len之間的元素逆置,可以實現最後的旋轉數組的目的。
代碼:
public void rotate(int[] nums, int k) { if(nums==null) return; int len=nums.length; k=k%len; if(k==0) return; int mid=len-k; int temp=0; int index=mid/2; for(int i=0;i