1. Introduction
The "Rotate Array" problem involves rotating the elements of an array to the right by k steps, where k is a non-negative integer. This problem tests the ability to manipulate array indices and understand modulo operations for circular rotations.
2. Problem
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
3. Solution in C++
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
Explanation:
1. Calculate k modulo the size of the array to handle cases where k is larger than the array size.
2. Reverse the entire array.
3. Reverse the first k elements.
4. Reverse the remaining n-k elements.
5. This sequence of reversals achieves the desired right rotation.
4. Solution in Java
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
Explanation:
1. Compute k modulo the array's length.
2. Reverse the entire array.
3. Reverse the first k elements.
4. Reverse the rest of the array.
5. This approach effectively rotates the array to the right by k steps.
5. Solution in Python
def rotate(nums, k):
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]
Explanation:
1. Calculate k modulo the length of nums to normalize k.
2. Slice the array into two parts: nums[n-k:] and nums[:n-k].
3. Concatenate these slices in reverse order to achieve the rotation.
4. This slicing and concatenating result in the array being rotated to the right by k steps.
Comments
Post a Comment