Skip to content

Latest commit

 

History

History
54 lines (42 loc) · 1.28 KB

001--Two Sum.md

File metadata and controls

54 lines (42 loc) · 1.28 KB
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Runtime: 1192 ms, faster than 33.33% of Python online submissions for Two Sum.
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            temp = target - nums[i]
            new_nums = nums[:i] + nums[i+1:]
            if temp in new_nums :
                j = new_nums.index(temp) + 1
                return [i, j]
        return [] 
Runtime: 20 ms, faster than 100.00% of Python online submissions for Two Sum.
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        map = {}
        for i in range(len(nums)):
            if nums[i] not in map:
                map[target - nums[i]] = i
            else:
                return map[nums[i]], i

        return -1, -1