java中通过双指针实现旋转数组:给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数
示例 1:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
示例 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
import java.util.Arrays;
public class _旋转数组 {
public static void main(String[] args) {
int[] nums = new int[]{-1,-5,-100,-88,99,1,8,6,1,7,6,2,5,4,13};
int k = 5;
_旋转数组 p = new _旋转数组();
p.rotate(nums, k);
System.out.println(Arrays.toString(nums));
}
public void rotate(int[] nums, int k) {
int left = 0;
int right = nums.length-k;
int[] ans = new int[nums.length];
while (right < nums.length) {
ans[left++] = nums[right++];
}
for (int i = 0; i < nums.length-k; i++) {
ans[left] = nums[i];
left++;
}
System.arraycopy(ans,0,nums,0,nums.length);
return;
}
}