</pre><pre>
https://leetcode.com/problems/rotate-array/
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]. 提供两种解法。 一种是 用hashmap来做,另外一种用arraycopy函数来做。时间复杂度类似。
第一种解法- HashMap
public class Solution {
public void rotate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = nums.length;
if( len > k) {
for(int i= len-k; i< len; i++) {
map.put(i - (len-k), nums[i]);
}
for (int i =0; i< len -k ; i++) {
map.put( i + k , nums[i]);
}
for(int j =0; j< map.size();j++)
nums[j]= map.get(j);
}
}
}
第二种 其他网友的解法 arraycopy
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] temp = new int[len];
if (len > k) {
// Refer : http://stackoverflow.com/questions/26610309/java-rotating-array
System.arraycopy(nums, 0, temp, k, len-k);
System.arraycopy(nums, len-k, temp, 0, k);
System.arraycopy(temp, 0, nums, 0, len); // nums[i] = temp[i], i= 0... len
}
if( len <k) { // this part is wroten by myself -hua
k = k%len;
System.out.println("k=" + k);
rotate(nums, k);
}
}
}