Check if two arrays are cyclic permutations

假装没事ソ 提交于 2019-12-21 03:57:23

问题


Given two arrays, how do you check if one is a cyclic permutation of the other?

For example, given a = [1, 2, 3, 1, 5], b = [3, 1, 5, 1, 2], and c = [2, 1, 3, 1, 5] we have that a and b are cyclic permutations but c is not a cyclic permutation of either.

Note: the arrays may have duplicate elements.


回答1:


The standard trick here is to concatenate one of the arrays with itself, and then try to find the 2nd array in the concatenated array.

For example, 'a' concatenated with itself is:

[1, 2, 3, 1, 5, 1, 2, 3, 1, 5]

Since you do see 'b' in this array starting from the 3rd element then a and b are cyclic permutations.




回答2:


If A and B are cyclic permutations of each other, A will be found in doubled list BB (as will B in AA).




回答3:


The efficient way to handle large amounts of data, is to transform each of them into a 'canonical' form then compare to see of they're equal. For this problem you can choose as the canonical form of all the rotated permutations the one that 'sorts smallest'.

So the canonical form for 'a' and 'b' is [1, 2, 3, 1, 5] which are equal so they are acyclic permutations.

The canonical form for 'c' is [1, 3, 1, 5, 2] which is different.




回答4:


Here is simple adhoc approach to findout cyclic permutations with O(n) time complexity.

a = [1, 2, 3, 1, 5], b = [3, 1, 5, 1, 2]

Find index of b[0] in a[], lets say index is 'x'.Then start navigating in both the array's. a[] starts from index 'x' and b[] starts from '0'. Such that both of them must have same values. If not, they are not cyclic. Here is the sample code.

 public class CyclicPermutation {

    static char[] arr = { 'A', 'B', 'C', 'D' };
    static char[] brr = { 'C', 'D', 'K', 'B' };
    boolean dec = false;

    public static void main(String[] args) {
        boolean avail = true;
        int val = getFirstElementIndex(brr[0]);
        if(val ==Integer.MIN_VALUE){
            avail = false; 
            return;
            }

        for (int i = val, j = 0; j <= brr.length-1; ) {
            if (i > arr.length-1) {
                i = 0;
            }
            if (arr[i] == brr[j]) {
                i++;

                j++;

            } else {
                avail = false;
                System.out.println(avail);
                return;
            }


        }

   System.out.println(avail);
    }

    public static int getFirstElementIndex(char c) {

        for (int i = 0; i <= arr.length; i++) {
            if (arr[i] == c) {
                return i;
            }
        }
        return Integer.MIN_VALUE;
    }


}


来源:https://stackoverflow.com/questions/6105087/check-if-two-arrays-are-cyclic-permutations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!