c++ - Why does my algorithm to rotate array right by k times without extra array running in O(n) work only for small arrays and not for big ones?
问题描述
I am trying to solve the Monk and Rotation problem given on HackerEarth (here) and I know other algorithms in the market that can do the work for me but I tried to make a new efficient algorithm for rotating array elements to the right by k times without using another array and without using any custom library functions and trying to run it in O(n). So, I came up with my solution where I started with the first element of the array and used a temp variable to store the first element and then swap temp with the element that will come at the array index after the rotation and then again swapping with the next position after rotation for that particular element and so on... I stop when the temp variable equals the starting element of the given array.
Note: I assume that all the elements are distinct
But the problem is that it works for me in my local system and also passes the test cases mentioned on the HackerEarth Website but I am not able to pass the rest of the private test cases there.
Below is my code for your reference:
#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;
}
An example of the test case:
1
5 2
1 2 3 4 5
My Output:
4 5 1 2 3
解决方案
Why my custom made algorithm [...] works only for small arrays and not for big arrays?
Because it is not guaranteed that with repeated i = (i+k)%n
increments you will visit all elements.
More specifically, this will only work when n and k have no common divisor (other than 1).
For instance, if n = 4 and k = 2, then the odd indices of your array will never be visited.
推荐阅读
- logging - 带有时间戳日志文件的 Cloudwatch 配置
- here-api - HERE 地图在手机上显示不好
- c# - 如何将列别名到另一个操作中
- visual-studio - 将 Microsoft Visual Studio Professional 2019 更新至版本 16.5.3 后,深色模式下的文本颜色发生了变化
- airflow - TFX Trainer 组件未将模型输出到文件系统的问题
- c - 在 c 中为链表创建结构时出现错误 C2061
- javascript - 我不明白 onClick={() => onClick()} (初学者问题)
- c++ - 计算 3d 点的像素坐标
- html - Angular 如何创建动态扩展复选框列表以及如何为 API 捕获价值?
- html - 如何在 Angular 中创建具有任意深度的文件夹结构?