检查两个数组是否是循环排列
给定两个数组,如何检查一个数组是否是另一个数组的循环排列?
例如,给定 a = [1, 2, 3, 1, 5]
、b = [3, 1, 5, 1, 2]
和 c = [2, 1, 3, 1, 5]
我们知道 a
和 b
是循环排列,但 c
是都不是循环排列。
注意:数组可能有重复的元素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里的标准技巧是将其中一个数组与其自身连接起来,然后尝试在连接的数组中找到第二个数组。
例如,“a”与其自身连接为:
[1, 2, 3, 1, 5, 1, 2, 3, 1, 5]
因为您确实在该数组中从第三个元素开始看到“b”,所以 a 和b 是循环排列。
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.
如果 A 和 B 是彼此的循环排列,则 A 将在双列表 BB 中找到(就像 B 在 AA 中一样)。
If A and B are cyclic permutations of each other, A will be found in doubled list BB (as will B in AA).
处理大量数据的有效方法是将它们转换为“规范”形式,然后进行比较以查看它们是否相等。对于这个问题,您可以选择“排序最小”的排列作为所有旋转排列的规范形式。
因此,“a”和“b”的规范形式是 [1, 2, 3, 1, 5],它们是相等的,因此它们是非循环排列。
“c”的规范形式是 [1, 3, 1, 5, 2],这是不同的。
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.
这是一种简单的临时方法,用于找出时间复杂度为 O(n) 的循环排列。
a = [1, 2, 3, 1, 5], b = [3, 1, 5, 1, 2]
在a[]中查找b[0]的索引,假设索引为'x'。然后开始
在两个数组中导航。 a[] 从索引 'x' 和 b[] 开始
从“0”开始。这样他们两个就必须具有相同的价值观。如果
不,它们不是循环的。
这是示例代码。
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.