public static void rotateArray(int[] nums, int k) {
k = Math.abs(k) % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotateArray(nums, k);
for (int num : nums) {
System.out.print(num + " ");
}
}
This code implements a function rotateArray
that rotates the elements of an integer array nums
by k
positions to the right. Here's a breakdown of the