简体   繁体   中英

Find if the name is present in three lists of equal size

I have three lists, each of which has n names. I have to find if there is a name in each of these lists and return it in lexicographical order. The time complexity has to be O(n*log(n)). I've tried the following approach:

  1. Sort each of three lists - that's 3n*log(n)
  2. Iterate through one list, and compare the name you're currently on to the names in other list, "forgetting" the ones you've already visited. On Python it should look something like this:
def find_name(arr1, arr2, arr3):
    arr1.sort()
    arr2.sort()
    arr3.sort()
    idx2 = idx3 = 0
    for name in arr1:
        while idx2 < len(arr2)-1 and name > arr2[idx2]:
            idx2 += 1
        while idx3 < len(arr3)-1 and name > arr3[idx3]:
            idx3 += 1
        if name == arr2[idx2] == arr3[idx3]:
            return name
    return -1

And it works on some inputs, but I still think I'm lacking something.

EDIT: I've updated my solution. It produces the same result as the Nick's solution, although his is obviously much faster (but my task requires exactly this one).

You can use set intersection to find the common names between each of the three lists; this is O(n) for the conversions and the intersection. Then you can take the minimum value of that set, also O(n). For example:

def find_name(arr1, arr2, arr3):
    s1 = set(arr1)
    s2 = set(arr2)
    s3 = set(arr3)
    common = s1.intersection(s2, s3)
    return min(common) if len(common) else -1

arr1 = ['bill', 'fred', 'nick', 'jim']
arr2 = ['john', 'nick', 'fred', 'jim']
arr3 = ['jim', 'fred', 'nick', 'joe']

print(find_name(arr1, arr2, arr3))

Output:

fred

If desired, this can be simplified to:

def find_name(arr1, arr2, arr3):
    common = set.intersection(set(arr1), set(arr2), set(arr3))
    return min(common) if len(common) else -1

or even further to:

def find_name(arr1, arr2, arr3):
    return min(set(arr1).intersection(arr2, arr3), default=-1)

Thanks to @solid.py and @superbrain for the code enhancements.

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.

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