是否有任何算法可从给定的成对数字列表中查找未成对数字。例如,在{(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. 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.
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:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.