How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

前端 未结 14 1978
萌比男神i
萌比男神i 2021-01-30 11:29

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

14条回答
  •  佛祖请我去吃肉
    2021-01-30 12:12

    def sum_in(numbers, sum_):
        """whether any two numbers from `numbers` form `sum_`."""
        a = set(numbers) # O(n)
        return any((sum_ - n) in a for n in a) # O(n)
    

    Example:

    >>> sum_in([200, -10, -100], 100)
    True
    

提交回复
热议问题