44 lines
1.0 KiB
Java
44 lines
1.0 KiB
Java
package com.zerroi.leetcode.ThreeFive;
|
||
|
||
import java.util.Arrays;
|
||
|
||
/**
|
||
* 给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
|
||
*/
|
||
public class Rotate {
|
||
public static void main(String[] args) {
|
||
|
||
}
|
||
}
|
||
|
||
class SolutionSecond {
|
||
public void rotate(int[] nums, int k) {
|
||
k = k % nums.length;
|
||
int[] temp = new int[k];
|
||
System.arraycopy(nums, nums.length - k, temp, 0, k);
|
||
|
||
for (int i = nums.length - k; i >= 0; i--) {
|
||
nums[i + k] = nums[i];
|
||
}
|
||
|
||
System.arraycopy(temp, 0, nums, 0, k);
|
||
}
|
||
|
||
public void rotateReverse(int[] nums, int k) {
|
||
k = k % nums.length;
|
||
reverse(nums, 0, nums.length);
|
||
reverse(nums, 0, k - 1);
|
||
reverse(nums, k, nums.length);
|
||
}
|
||
|
||
public void reverse(int[] nums, int start, int end) {
|
||
while (start < end) {
|
||
int temp = nums[start];
|
||
nums[start] = nums[end];
|
||
nums[end] = temp;
|
||
start += 1;
|
||
end -= 1;
|
||
}
|
||
}
|
||
}
|