Easy to understand O(n) python Solution with explanation

  • 0

    class Solution(object):
    def twoSum(self, nums, target):
    Using a map, iterate over nums storing the difference of the target
    and the current element with the value being the index. If the key is in the
    map, return the value stored and the current index.
    vals = {}
    for i, num in enumerate(nums):
    if num in vals:
    return [vals[num], i]

            val = target - num
            vals[val] = i
        return []

Log in to reply

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