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

@qzl/typed-i18n — Our Open-Source Typed i18n Project is Gaining Traction

 Hello everyone! 👋 We are excited to share an update about one of our open-source projects , @qzl/typed-i18n , created by the QZ-L.com team...