算法 - 圆阵旋转

时间:2017-03-05 02:19:12

标签: c++ arrays algorithm

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

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;
     }

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在std :: array上使用stl :: rotate,你可以将其旋转,例如2,as:

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,或者右转,比如2,如:

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

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

答案 2 :(得分:0)

nk方向上left次旋转长度为right的数组。

  

代码是Java

我定义了一个方向枚举:

public enum Direction {
    L, R
};

使用timesdirection进行轮播:

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]