Check if two arrays are cyclic permutations

前端 未结 4 1128
情歌与酒
情歌与酒 2021-02-14 08:41

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], an

4条回答
  •  天命终不由人
    2021-02-14 08:52

    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.

提交回复
热议问题