LeetCode/com/zerroi/leetcode/ThreeFive/Rotate.java

44 lines
1.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}