189. Rotate Array (Approach 1 )
Intitution
Complexity
Space Complexity
Time Complexity
Code
public void rotate(int[] nums, int k) {
k = k % nums.length; // Handle cases where k >= nums.length
if (k == 0) return; // No need to rotate
// Step 1: Duplicate the array (simulate circular behavior)
int[] numsDuplicated = new int[2 * nums.length];
for (int i = 0; i < nums.length; ++i) {
numsDuplicated[i] = nums[i];
numsDuplicated[nums.length + i] = nums[i]; // Append the same array
}
// Step 2: Copy the rotated portion back into the original array
for (int i = 0; i < nums.length; ++i) {
nums[i] = numsDuplicated[nums.length - k + i];
}
}Last updated