"R-r-riddikulus" used in the movie Harry Potter to transform anything from one form to another, Similarly you have to transform the array by rotation.
A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array a of n integers and a number, d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.
Example:
Input: n = 5, d = 4, a = [1, 2 ,3 ,4, 5]
Output: 5 1 2 3 4
Approach
C++
#include <bits/stdc++.h>using namespace std;void shiftDNumbers(int n, int d, int a[]){int f[d];for (int i = 0; i < d; i++)f[i] = a[i];int l = 0;for (int i = d; i < n; i++)a[l++] = a[i];for (int i = 0; i < d; i++)a[l++] = f[i];for (int i = 0; i < n; i++)cout << a[i] << " ";cout << "\n";}int main(){int n = 5, d = 4;d = d % n;int a[n] = {1, 2, 3, 4, 5};shiftDNumbers(n, d, a);return 0;}
No comments:
Post a Comment