[英]Finding Unpaired Numbers From Given Number Pairs
是否有任何算法可从给定的成对数字列表中查找未成对数字。例如,在{(1,2),(2,3),(3,4)}中,成对(1,3)和(2,4 )从未配对过。
You could do this as follows: 您可以按照以下步骤进行操作:
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.