为什么我因超时而被终止'错误在这里?

时间:2016-09-21 14:14:58

标签: c++ arrays algorithm

我在Hackerrank上解决this problem

John Watson在一个整数数组上执行一个称为右旋转的操作,[a [0],a [1] ...... a [n]]。执行一次右旋转操作后,数组从[a [0],a [1] ...... a [n]]转换为[a [n-1],a [0] ...... a [n-2] ]

Watson执行此操作' k'倍。为了测试Sherlock识别旋转阵列中特定位置的当前元素的能力,Watson要求q'查询,其中每个查询由一个整数组成,' m',您必须在旋转数组中的索引处打印元素(即a [m]的值)。

输入格式

第一行包含3个以空格分隔的整数,&#39; n&#39; &#39; K&#39;和,&#39; q&#39;分别。 第二行包含&#39; n&#39;空格分隔的整数,其中每个整数&#39; i&#39;描述了数组元素a [n](其中0 <= i

输出格式

对于每个查询,在索引&#39; m&#39;处打印元素的值。旋转的数组在新行上。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */   
int n,k,q,temp;
cin>>n>>k>>q;       //Input of n,k,q;
int arr[n],qur[q];
for(int i=0;i<n;i++)    //Input of array
{
    cin>>arr[i];
}
    for(int i=0;i<q;i++)    //Input of query numbers
{
        cin>>qur[i];
}

for(int z=0;z<k;z++)
{
    temp = arr[n-1];
    for(int i=n-1;i>0;i--)
    {
        arr[i]=arr[i-1];
    }
    arr[0]=temp;
}

for(int i=0;i<q;i++)
{
    cout<<arr[qur[i]]<<endl;
}


return 0;
 }

代码的逻辑似乎完美无瑕。我是新手。谢谢。

1 个答案:

答案 0 :(得分:1)

原因是你不需要进行轮换,你可以使用古代数学力量 (执行轮换可能需要100亿arr[i]=arr[i-1]秒,并且执行500次需要一段时间。)

如果您从序列开始

Element: | 12 | 34 | ... | 56 | 78 |           (1)
Index:      0    1   ...   k-1   k

然后向右旋转一下,你得到

Element: | 78 | 12 | 34 | ... | 56 |           (2)
Index:      0    1    2   ...    k

或者,稍微改变一下观点:

Element: | 12 | 34 | ... | 56 | 78 |           (3)
Index:      1    2   ...    k    0

(1)和(3)中元素的索引之间有一个相当简单的关系,你只需要一些算术从一个到另一个。

发现关系并将算术作为练习。

相关问题