简体   繁体   English

C#-Array2包含Array1忽略顺序

[英]C# - Array2 contains Array1 ignore order

Where should I look if I want to write a piece of code which looks for Array1 in Array2, regardless of the order (keeping the duplicates in mind)? 如果要编写一段在Array2中查找Array1的代码,而不考虑顺序(记住重复项),我应该在哪里看? eg 例如

Array1: { 2,5,6,6,3 }
Array2: { 1,2,3,4,5,6,6 }
will return true


Array1: { 2,5,6,6,3 }
Array2: { 1,2,3,4,5,6 }
will return false

I sort of want to solve it myslef, I just need to be pointed in some direction. 我有点想解决这个问题,我只需要指出一些方向。

Thanks in advance. 提前致谢。

Well, since you only want hints rather than code, one method would be: 好吧,由于您只需要提示而不是代码,因此一种方法是:

  1. Copy array2 into a List<int> . array2复制到List<int>

  2. Sort it . 排序

  3. Allocate a bit array called used equal to the size of the list. 分配一个位阵列称为used等于所述列表的大小。 These will be flags indicating whether a specific item in the sorted list has been used for a match. 这些将是标志,指示已排序列表中的特定项目是否已用于匹配。

  4. For each item item in array1 : 对于每个项目itemarray1

    4.1 Binary search the sorted list for item . 4.1 二进制搜索排序列表item

    4.2. 4.2。 If not found, return false -- array2 does not contain array1 . 如果未找到,则返回false - array2不包含array1

    4.3. 4.3。 If found, and there are duplicates, the binary search algorithm will randomly return the index of one of the duplicates. 如果找到,并且有重复项,则二进制搜索算法将随机返回其中一个重复项的索引。 Scan backward in the portion of the list that matches item until you find one for which used[i] is false. 在列表中与item匹配的部分中向后扫描,直到找到used[i]为false的项目。 If you find one, set used[i] to true, and continue the outer loop. 如果找到一个,则将used[i]设置为true,然后继续外部循环。 If you don't find one, scan forward from the initial binary search index, trying to find an unused match. 如果找不到,请从初始二进制搜索索引向前扫描,尝试查找未使用的匹配项。 Similarly set used[index] to true if one is found, and continue looping through array1 . 类似地,如果找到一个,则将used[index]设置为true,并继续遍历array1

    4.4 If no unused match is found, return false -- array2 does not contain array1 . 4.4如果未找到未使用的匹配项,则返回false- array2不包含array1

  5. Having found an unused match for each item in array1 , return true: array1 is contained inside array2 . 找到array1每个项目的未使用匹配项后,返回true: array1包含在array2内部。

An advantage of this algorithm is that, to check multiple arrays for being contained in a given array, you don't need to re-sort the array every time, you only need to re-allocate the BitArray . 该算法的一个优点是,要检查多个数组是否包含在给定数组中,您不需要每次都对数组进行重新排序,只需要重新分配BitArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM