Python with bisect


  • 0
    N

    Using bisect.bisect to do binary search, and also use the return value to shrink the scope. It takes 59 ms.

    class Solution(object):
        def twoSum(self, numbers, target):
            """
            :type numbers: List[int]
            :type target: int
            :rtype: List[int]
            """
            start = 0
            end = len(numbers)
    
            while start < end:
                index = bisect.bisect(numbers, target - numbers[start], start, end)
                if index <= end and numbers[index - 1] == target - numbers[start]:
                    return [start + 1, index]
                else:
                    start += 1
                    end = index
                    continue
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.