Choosing mutually exclusive pairs efficiently

前端 未结 4 1920
滥情空心
滥情空心 2021-01-17 19:12

This is a problem that could be done with some type of brute-force algorithm, but I was wondering if there are some efficient ways of doing this.

Let\'s assume that

4条回答
  •  逝去的感伤
    2021-01-17 19:40

    Edit: This won't work as user98235 points out in the comments. I will leave this here however in case anyone else has the same idea.

    I think this will work if I have understood the problem correctly.

    Pseudocode:

    resultList = new List of Pair
    elementSet = new Set of int
    
    for pair in inputPairs:
    
        if not elementSet.Contains(pair.First) and not elementSet.Contains(pair.Second):
            elementSet.Add(pair.First)
            elementSet.Add(pair.Second)
            resultList.Add(pair)
    

    The time complexity will be O(N).

提交回复
热议问题