【问题标题】:Efficient way to rotate array clockwise and counterclockwise顺时针和逆时针旋转阵列的有效方法
【发布时间】:2014-09-08 06:45:03
【问题描述】:

我在 C++ 中顺时针和逆时针旋转数组或向量。就时间复杂度而言,哪种方法最有效? 我使用了 rotate() 函数,但我想知道有没有比这更快的方法?

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

int main()
{
   vector<int> v;
   for(int i=0;i<5;i++)
      v.push_back(i);
   int d=2;
   rotate(v.begin(),v.begin()+d,v.end());
   return 0;
}

【问题讨论】:

    标签: c++ algorithm vector rotation


    【解决方案1】:

    rotate() 是一个线性时间函数,这是你能做的最好的。

    但是,如果你需要做多次旋转,你可以累积。

    例如: 旋转 4 和旋转 5 与单旋转 9 相同。

    或者实际上,在某些应用程序中,您甚至可能不想实际旋转。

    比如,如果你想按 'd' 旋转。您可以只创建一个函数,在被要求输入 v[i] 时返回 v[(i+d)%v.size()]。这是恒定时间的解决方案。但就像我说的,这是特定于应用程序的。

    【讨论】:

      【解决方案2】:

      我可以让 XY 更快吗?”这类问题的一般答案: 也许你可以。但可能你不应该这样做。

      std::rotate 旨在对一般情况有效。这意味着,如果您有一个非常具体的案例,可能可以为该案例提供更高性能的实现。

      但是:

      • 不必费心去实现它,因为您必须对其进行测试,但您对极端情况的覆盖率仍然不如标准库实现已经执行的测试。
      • 不要使用它,因为有人会生气,问自己为什么要推出自己的实现而不只是使用标准库。其他人会将其用于性能不如标准实现的情况。
      • 不要花时间来提高一段清晰代码的性能,除非你 100% 确定它是性能瓶颈。 100% 确定意味着,您使用了分析器并查明了瓶颈的确切位置。

      【讨论】:

        【解决方案3】:
        #include <bits/stdc++.h>
        #include <iostream>
        using namespace std;
        
            void rotatebyone(int arr[], int n) {
            int temp= arr[0], i;
            for(i=0;i<n;i++)
            {
              arr[i]=arr[i+1];
              arr[n]=temp;
            }
          }
        
        int main()
        {
            int arr[]={2,3,4,5,6,7,8};
            int m= sizeof(arr)/sizeof(arr[0]);
            int i;
            int d=1;
        
            for(i=0;i<d;i++) {          //function to implement it d no of times
                rotatebyone(arr,m);
            }
        
            for(i=0;i<m;i++) {
                cout<<arr[i]<<"";
            }
        
        return 0;
        }
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-26
        相关资源
        最近更新 更多