【问题标题】:In Place rotation C++ Practice就地轮换 C++ 实践
【发布时间】:2009-11-11 18:48:44
【问题描述】:

我有一个适用于我的“items”int 数组的旋转函数。下面的代码完成了它,除了我不必要地传输值。我试图实现“就地”旋转。我的意思是,ptrs 将递增或递减,而不是从数组中获取值。通过这种方式,我需要以这种方式“提高”这种方法的效率水平。有什么建议吗?

void quack::rotate(int nRotations)
{
 if ( count <= 1 ) return;
 else  // make sure our ptrs are where we want them.
 {
  intFrontPtr = &items[0].myInt;
  intBackPtr  = &items[count-1].myInt;
 }
 for (int temp = 0; nRotations != 0;)
 {
  if ( nRotations > 0 )
  {
     temp = *intFrontPtr;
    *intFrontPtr = *intBackPtr;
    *intBackPtr  = temp; // Connect temps for the rotation
   --intBackPtr; // Move left [...<-] into the array
  }
  else if ( nRotations < 0 ) 
  {
   temp = *intBackPtr;
   *intBackPtr  = *intFrontPtr;
   *intFrontPtr = temp; // Connect temps for the rotation
   ++intFrontPtr; // Move right [->...] into the array
  }
  if ( intBackPtr  == &items[0].myInt  || 
    intFrontPtr == &items[count-1].myInt ) 
  {
   intFrontPtr = &items[0].myInt; 
   intBackPtr  = &items[count-1].myInt; // need to re-set
   if ( nRotations > 0 ) nRotations--;  // Which ways did we rotate?
   else nRotations++;
  }
 }
 }

哦,是的,我正在尝试练习 C++,并且知道它们有许多浮动的函数,这些函数已经被编程为执行此操作……我正在尝试“构建我自己的”。我想我在语法上已经把它记下来了,但效率总是我挣扎的地方。作为一个新手,我将不胜感激批评这方面..

【问题讨论】:

    标签: c++ arrays rotation


    【解决方案1】:

    在数组中旋转元素有一个古老的技巧(我第一次看到它是在 Programming Pearls 中)

    假设您要将数组向左旋转三个元素。

    先反转前三个元素,再反转其余元素,再反转整个数组。

    Starting Array:
    1 2 3 4 5 6 7
    
    After reversing the first three elements
    3 2 1 4 5 6 7
    
    After reversing the remaining elements
    3 2 1 7 6 5 4
    
    Finally reverse the entire array to get the final rotated array
    4 5 6 7 1 2 3
    

    数组的反转部分可以就地完成,因此您不需要任何额外的内存。

    【讨论】:

    • 那不是将数组向左旋转吗?
    • 绝招。虽然你总是移动一个元素两次,而它可以一次完成。
    • @reinier - 你如何将数组旋转任意数量的位置,同时只触摸每个元素一次?
    • @sdtom:你提到了“编程珍珠”,对吧?同一个“编程珍珠”中的“杂耍算法”只触及每个元素一次(即每个元素一次读取,一次写入)
    • @reinier:虽然“杂耍算法”一气呵成,但在合理的算法中效率最低。对于相当大的输入,最有效的算法是“Programming Pearls”中的“block swap”。而且它还会多次移动元素。
    【解决方案2】:

    您可以保留数据,并拥有一个“基本索引”成员来指示数组应该从哪里开始。然后,您需要在访问数组时使用它来调整索引。数组本身应该是私有的,并且只能通过进行调整的访问器函数访问。像这样的:

    class quack
    {
    public:
        explicit quack(int size) : items(new Item[size]), size(size), base(0) {}
        ~quack() {delete [] items;}
    
        void rotate(int n)      {base = (base + n) % size;}
        Item &operator[](int i) {return items[(base + i) % size];}
    
    private:
        quack(quack const&) = delete;          // or implement these if you want
        void operator=(quack const&) = delete; // the container to be copyable
    
        Item *items;
        int   size;
        int   base;
    };
    

    虽然我会称它为RotatableArray,而不是quack。

    【讨论】:

      【解决方案3】:

      像往常一样,如果你真的需要对元素进行物理旋转,那么 C++ 的正确答案是使用 std::rotate,这正是你想要做的。

      如果您必须手动实现它(作为练习作业),请查看这些 slides 以了解 John Bentley 的“Programming Pearls”中的算法。

      【讨论】:

        【解决方案4】:

        逐个进行轮换确实不是要走的路。如果你做的任何事情超过 2 或 3 次旋转,它就会变得非常慢非常快。

        编辑: 作为最后的想法......将元素放在(双)链接的“循环”列表中(因此最终元素指向第一个),将需要旋转仅将头指针移动几个元素。 (头指针是指示循环列表中哪个元素是开始的指针)。

        这是迄今为止对元素列表进行旋转的最快(也是最简单)的方法

        【讨论】:

          【解决方案5】:

          真正做到这一点的方法是使用索引而不是指针。

          int to = 0;
          int from = (to + nRotations) % count;
          if (to == from)
              return;
          
          for (int i=0; i < count; i++) {
             swap(from, to);
             from = advance(from);
             to = advance(to);
          }
          
          // ...
          static inline int advance(int n, int count) { return (n + 1) % count; }
          

          【讨论】:

            【解决方案6】:

            我可能有一个替代解决方案来内联旋转数组。与之前提出的反转元素集的旧技巧不同,这种方法的工作原理如下:

            初始化:

            (注q = 左移量,n = 数组长度)

            1. 确定第一个源元素,它位于 x1=q%n
            2. 目标元素位于 x2=0
            3. char,ch1,是 ar[x1] 元素
            4. char,ch2,是 ar[x2] 元素

            循环 i=0 到 n-1,其中 n = 数组长度

            1. 用 ch1 覆盖目标元素 ar[x2]
            2. 设置 ch1 = ch2
            3. 设置 x1 = x2
            4. 设置 x2 = x2 - q
            5. 如果由于上述减法,x2 为负数,则将 n 添加到其中
            6. ch2 = ar[x2]

            以下内容可能有助于解释其工作原理。

            例如,向左旋转 2 个字符:

            a b c d e f g

            c d e f g a b

            x1    ch1    x2    ch2
            2     c      0     a
            0     a      5     f
            5     f      3     d
            3     d      1     b
            1     b      6     g
            6     g      4     e
            4     e      2     c
            

            如您所见,这需要不超过 n 次迭代,因此它是线性时间算法,也可以内联旋转(除了几个临时变量之外不需要额外的存储空间)。

            这里有一个实现上述算法的函数,大家可以试试:

            void rotate(char *ar, int q)
            {
                if (strlen(ar) < 2)
                {
                    return;
                }
            
                if (q <= 0)
                {
                    return;
                }
            
                char ch1;
                char ch2;
                int x1;
                int x2;
                int i;
                int n;
            
                n = strlen(ar);
            
                q %= n;
            
                if (q == 0)
                {
                    return;
                }
            
                x1 = q;
                ch1 = ar[x1];
                x2 = 0;
                ch2 = ar[x2];
            
                for (i=0;i<n;i++)
                {
                    ar[x2] = ch1;
                    ch1 = ch2;
            
                    x1 = x2;
            
                    x2 -= q;
            
                    if (x2 < 0)
                    {
                        x2 += n;
                    }
            
                    ch2 = ar[x2];
                }
            }
            

            【讨论】:

            • 我觉得不对。考虑abcdef 并左移2,结果将是cbadcf 而不是cdefab。
            【解决方案7】:

            这是我修改代码here得到的一个:

            template<class It>
            It rotate(It begin, It const middle, It end)
            {
                typename std::iterator_traits<It>::difference_type i = 0, j;
                if (begin != middle && middle != end)
                {
                    while ((i = std::distance(begin, middle)) !=
                           (j = std::distance(middle,   end)))
                    {
                        It k = middle;
                        std::advance(
                            k,
                            std::max(typename std::iterator_traits<It>::difference_type(),
                            j - i));
                        std::swap_ranges(k, end, begin);
                        if (i > j) { std::advance(begin, j); }
                        else { std::advance(end, -i); }
                    }
                }
                return std::swap_ranges(middle - i, middle, middle);
            }
            

            【讨论】:

              【解决方案8】:

              这是sdtom解决方案的代码

              void rotateArray(int arr[], int low, int high)
              {
                  while  (low<high) {
                      int temp = arr[low];
                      arr[low]=arr[high];
                      arr[high]=temp;
                      low++;
                      high--;
                  }
              }
              void rotate (int arr[], int k,int uperLimit)
              {
                  rotateArray(arr,0,k);
                  rotateArray(arr,k+1,uperLimit-1);
                  rotateArray(arr,0,uperLimit-1);
              
              }
              

              【讨论】:

                【解决方案9】:

                https://stackoverflow.com/q/17119000/2383578 :这有点类似于这里讨论的内容。将数组旋转特定的量。

                【讨论】:

                  【解决方案10】:

                  有很多方法可以按 d 个位置进行数组旋转。

                  1. 块交换算法。
                  2. 杂耍算法。
                  3. 反转算法。

                  以下链接来自 Programming Pearls pdf。看一下这个。用代码解释得很清楚。

                  http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf

                  【讨论】:

                  • 链接已失效。
                  猜你喜欢
                  • 1970-01-01
                  • 2021-08-11
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-11
                  • 2021-08-11
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多