Array Right Shift K Steps

Question:
An array has N numbers, move each elements to right for K steps.
time limit : O(N)
e.g.
abcd1234 move 4 steps turns out
1234abcd
Answer:
void Reverse(int* arr, int b, int e)
{
for (; b < e; b++, e--) {
int temp = arr[e];
arr[e] = arr[b];
arr[b] = temp;
}
}
void RightShift(int* arr, int N, int K)
{
K %= N;
Reverse(arr, 0, N - K - 1);
Reverse(arr, N-K, N-1);
Reverse(arr, 0, N-1);
}

No comments:

Post a Comment

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...