Problem: Given an array, rotate the array to the right by k steps, where k is non-negative.
Example (taken from leetcode):
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Approach: Reverse the whole array. Reverse 1st k elements and then reverse the rest of n-k elements. Now k could be more than n so we can initialize k as k = k mod n.
Implementation in C#:
public static void Rotate(int[] nums, int k)
{
if (nums?.Length <= 1)
{
return;
}
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 startIndex, int endIndex)
{
for (int i = startIndex, j = endIndex; i < j; ++i,--j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
Complexity: O(n)
No comments:
Post a Comment