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: It can be achieved in three steps:
- Reverse the whole array.
- Reverse 1st k elements.
- Reverse the rest of n-k elements. That means reverse subarray arr[k...n-1]
Now k could be more than n so we can initialize k as k = k mod n.
Implementation in C#:
public void Rotate(int[] nums, int k)
{
int length = nums?.Length ?? 0;
if (length <= 1)
{
return;
}
k = k % length;
this.Reverse(nums, 0, length - 1);
this.Reverse(nums, 0, k - 1);
this.Reverse(nums, k, 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;
}
}
Complexity: O(n)
No comments:
Post a Comment