K-Rotate
K-Rotate
Given an integer vector and a value k, your task is to rotate the array k times clockwise.
Input Format
In the function an integer vector and number k is passed.
Output Format
Return an integer vector.
Sample Input
- {8, 2, 5, 7, 6}, x = 2
Sample Output
- {7,6,8,2,5}
Explanation
- After 1st rotation - {7,6,8,2,5}
- After 2nd rotation - {7,6,8,2,5}
- Program -
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
vector<int> kRotate(vector<int> a, int k){
// Using second vector (array) solution
int l = a.size();
k = k%l;
vector<int> out;
for(int i=l-k;i<l;i++){
out.push_back(a[i]);
}
for(int i=0;i<l-k;i++){
out.push_back(a[i]);
}
return out;
}
vector<int> kRotate2(vector<int> a, int k){
// same memory solution
int l = a.size();
k = k%l;
reverse(a.begin(),a.begin()+l-k);
reverse(a.begin()+l-k,a.end());
reverse(a.begin(),a.end());
return a;
}
int main(){
cout<<"OutPut = ";
vector<int> Out;
vector<int> test_in ={8, 2, 5, 7, 6}; // Define Vector
/* Frist solution Output */
Out = kRotate(test_in,1);
for(int x : Out){
cout<<x<<',';
}
cout<<endl;
/* Seconed solution OutPut*/
Out = kRotate2(test_in,1);
for(int x : Out){
cout<<x<<',';
}
cout<<endl;
}
Comments
Post a Comment