2017-03-05 60 views
1

圆形阵列旋转的线性复杂性实现是否正确?算法 - 圆形阵列旋转

N =元素数目 K =转

int write_to  = 0; 
    int copy_current = 0; 
    int copy_final = a[0]; 
    int rotation  = k; 
    int position  = 0; 

    for (int i = 0; i < n; i++) { 
     write_to  = (position + rotation) % n; 
     copy_current = a[write_to]; 
     a[write_to] = copy_final; 
     position  = write_to; 
     copy_final = copy_current; 
    } 
+0

好,复杂度是线性的肯定。但是如果你希望通过'#rotation'位置来旋转数组中的值,传统上将其描述为循环旋转,当这不是最终结果时,你会感到惊讶。 –

+0

http://stackoverflow.com/questions/11893053/circular-left-shift-of-an-array-by-n-positions-in-java – vadim

+2

@vadim:对这个问题的接受答案肯定是正确的,但更漂亮解决方法是:1.反转第k个元素。 2.反转其余的元素。 3.反转整个阵列。 (所有反转都在原地。) – rici

回答

0

考虑这个例子的数目。

#include <iostream> 

int main(void) { 
    int n = 6; 
    int k = 2; 
    int a[] = {1, 2, 3, 4, 5, 6}; 

    int write_to  = 0; 
    int copy_current = 0; 
    int copy_final = a[0]; 
    int rotation  = k; 
    int position  = 0; 

    for (int i = 0; i < n; i++) { 
     write_to  = (position + rotation) % n; 
     copy_current = a[write_to]; 
     a[write_to] = copy_final; 
     position  = write_to; 
     copy_final = copy_current; 
    } 

    for (int i = 0; i < n; i++) { 
     std::cout << a[i] << (i + 1 < n ? ' ' : '\n'); 
    } 
    return 0; 
} 

预期结果:

5 6 1 2 3 4 

实际结果:

3 2 1 4 1 6 
0

使用STL ::旋转上的std ::阵列,可以循环左移的话,比如说2,如:

std::array<int, 6> a{1, 2, 3, 4, 5, 6}; 
std::rotate(begin(a), begin(a) + 2, end(a)); // left rotate by 2 

,得到:3 4 5 6 1 2,或右键RO tate by,say 2,as:

std::rotate(begin(a), end(a) - 2, end(a)); // right rotate by 2 

产生:5 6 1 2 3 4,具有线性复杂性。

0

旋转数组长度为nk次在leftright方向。

该代码是用Java

我定义了一个方向枚举:

旋转与 timesdirection
public enum Direction { 
    L, R 
}; 

public static final void rotate(int[] arr, int times, Direction direction) { 
    if (arr == null || times < 0) { 
     throw new IllegalArgumentException("The array must be non-null and the order must be non-negative"); 
    } 
    int offset = arr.length - times % arr.length; 
    if (offset > 0) { 
     int[] copy = arr.clone(); 
     for (int i = 0; i < arr.length; ++i) { 
      int j = (i + offset) % arr.length; 
      if (Direction.R.equals(direction)) { 
       arr[i] = copy[j]; 
      } else { 
       arr[j] = copy[i]; 
      } 
     } 
    } 
} 

复杂度:O(N )。

实施例: 输入:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 旋转3left 输出:[4, 5, 6, 7, 8, 9, 10, 1, 2, 3]

输入:[4, 5, 6, 7, 8, 9, 10, 1, 2, 3] 旋转3right 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

+0

尽管这可能会回答这个问题,但最好解释答案的重要部分,以及OPs代码可能存在的问题。 – pirho

+0

你没有回答这个问题('这是线性复杂的圆形阵列旋转实现是否正确?'),但只是提出解决方案的基本问题没有任何评论。如果你解释为什么和什么,它总是值得赞赏的。 – fragmentedreality