简体   繁体   English

查找名称是否存在于三个大小相等的列表中

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

I have three lists, each of which has n names.我有三个列表,每个列表都有 n 个名字。 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)).时间复杂度必须为 O(n*log(n))。 I've tried the following approach:我尝试了以下方法:

  1. Sort each of three lists - that's 3n*log(n)对三个列表中的每一个进行排序 - 即 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:在 Python 上,它应该看起来像这样:
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).它产生的结果与 Nick 的解决方案相同,尽管他的解决方案显然要快得多(但我的任务恰好需要这个)。

You can use set intersection to find the common names between each of the three lists;您可以使用 set intersection 来查找三个列表中每个列表之间的公共名称; this is O(n) for the conversions and the intersection.这是转换和交集的 O(n)。 Then you can take the minimum value of that set, also O(n).然后你可以取该集合的最小值,也就是 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: 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.感谢@solid.py 和@superbrain 的代码改进。

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

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