我正在尝试解决 HackerEarth (here) 上给出的 Monk 和 Rotation 问题,我知道市场上可以完成这项工作的其他算法对我来说,但我尝试制作一种新的高效算法,将数组元素向右旋转 k 次不使用另一个数组,也不使用任何自定义库函数并尝试运行它在O(n)。所以,我想出了我的解决方案,我从数组的第一个元素开始,并使用 temp 变量来存储第一个元素,然后将 temp 与该元素交换将在旋转后出现在数组索引处,然后再次与该特定元素旋转后的下一个位置交换,依此类推......当 temp 变量等于给定数组的起始元素时,我停止.
注意:我假设所有元素都是不同的
但问题是它在我的本地系统中对我有用,并且还通过了 HackerEarth 网站上提到的测试用例,但我无法通过那里的其余私有测试用例。
以下是我的代码供您参考:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<string,string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
int main() {
ll t,temp;
cin >> t; //inputing test cases
while(t--){
vl arr;
ll i,n,k;
cin>>n>>k;
for(i=0;i<n;i++){ //inputing array
cin>>temp;
arr.push_back(temp);
}
/*Main Algo*/
ll temp1 = arr[0];
temp = arr[0];
while(1){
i = (i+k)%(n);
swap(arr[i],temp);
//cout<<"temp: "<<temp<< endl;
if(temp == temp1)break;
}
//Printing Rotated Array
for(i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
return 0;
}
测试用例示例:
1
5 2
1 2 3 4 5
我的输出:
4 5 1 2 3