简体   繁体   English

从给定的数字对中查找未配对的数字

[英]Finding Unpaired Numbers From Given Number Pairs

是否有任何算法可从给定的成对数字列表中查找未成对数字。例如,在{(1,2),(2,3),(3,4)}中,成对(1,3)和(2,4 )从未配对过。

You could do this as follows: 您可以按照以下步骤进行操作:

  1. Iterate over all the pairs and build up a set of all the numbers that appear in the set. 遍历所有对,并建立一组出现在集合中的所有数字。
  2. Construct all possible pairs of numbers, storing the result in a different set. 构造所有可能的数字对,将结果存储在不同的集合中。
  3. Iterate over all the pairs from the original list, and remove each one that you find from the set of all pairs. 遍历原始列表中的所有对,然后从所有对的集合中删除找到的每个对。
  4. You are now left with all pairs that did not appear in the original set. 现在,您将剩下未出现在原始集中的所有对。

Of course, this assumes that you only care about pairs of values from the original set. 当然,这假定您只关心原始集中的值对。 For example, the pair (1, 5) wasn't in your example either. 例如,在您的示例中也不存在(1,5)对。 Neither was (cat, dog). 两者都不是(猫,狗)。

This runs in time O(n 2 ), where n is the number of numbers represented in the original set of pairs. 这在时间O(n 2 )中运行,其中n是原始对对中表示的数字数。

Hope this helps! 希望这可以帮助!

Using LINQ and a symmetry trick taking advantage of the fact that (1,3) and (3,1) are identical, so ignoring cases where the second number is bigger than the first: 使用LINQ和对称技巧来利用(1,3)和(3,1)相同的事实,因此忽略第二个数字大于第一个数字的情况:

public static IEnumerable<Tuple<int, int>> GetUnpairedNumbers(IEnumerable<Tuple<int, int>> existingPairs ) {
    var uniqueNumbers = existingPairs.SelectMany(p => new[] {p.Item1, p.Item2}).Distinct().ToList();
    var isUsed = uniqueNumbers.ToDictionary(n => n, n => uniqueNumbers.Where(inner => n < inner).ToDictionary(inner => inner, inner => false));

    foreach(var currentPair in existingPairs) {
        isUsed[currentPair.Item1][currentPair.Item2] = true;
    }

    return isUsed.Keys.SelectMany(n => isUsed[n].Where(kvp => !kvp.Value).Select(kvp => Tuple.Create(n, kvp.Key)));
}
public static void Main(string[] args) {
    var unpairedNumbers = GetUnpairedNumbers(new[] { P(1, 2), P(2, 3), P(3, 4) });
}

private static Tuple<int, int> P(int a, int b) {
    return Tuple.Create(a, b);
}

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

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