Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
[1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]Analysis:
This is a tricky question and is hard to come up with a neat solution at first glance.
Turns out the answer is pretty simple, be careful about sanity check for value of k.
Solution:
void reverse(int *nums, int start, int end)
{
if(start > end)
return;
int i = start, j = end;
while(i < j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
void rotate(int nums[], int n, int k) {
k = k % n; -> The sanity check is a bit tricky
if(k>0 && k< n)
{
// reverse whole thing first
reverse(nums, 0, n -1);
// reverse first k elements, then reverse the rest
reverse(nums, 0, k-1);
reverse(nums, k, n-1);
}
}
Further thoughts:
Not much to say about question like this. Most ppl could finish it with hint.
No comments:
Post a Comment