Python Solution - in 5 lines


  • 0

    I try to using a nested for loop, the time complexity is O (n ^ 2);
    I try to using binary search , but the array is unsorted;
    the hash table method, the time complexity is O (n).

        def twoSum(self, nums, target):
            d = { }
            for i, n in enumerate(nums):
                if target - n in d:
                    return [min(i, d[target-n]), max(i, d[target-n])]
                d[n] = i
    

  • 0
    E

    Just return [d[target-n], i], since the hashtable d you built will always return a smaller value compare to i

    @Yuukir said in Python Solution - in 5 lines:

    I try to using a nested for loop, the time complexity is O (n ^ 2);
    I try to using binary search , but the array is unsorted;
    the hash table method, the time complexity is O (n).

        def twoSum(self, nums, target):
            d = { }
            for i, n in enumerate(nums):
                if target - n in d:
                    return [min(i, d[target-n]), max(i, d[target-n])]
                d[n] = i
    

Log in to reply
 

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