LeetCode 1: Two Sum

LeetCode 1: Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Analysis

Use python dict structure to solve it.

Store array to an dict. Let’s assume x is a number in array. If both x and (target-x) are in the dict, then they are what we are looking for.

Pay attention to an exception:

If target is twice x, we should take extra effort. Details are in codes explanation.

Solution

Python codes

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = []
        d = {}
        
        """
        : Store list value and index to dict: dict[value] = index + 1
        : If list cantains many same value and target is twice value, return the two values' indexes
        """
        for index, x in enumerate(nums, 1):
            if x not in d:
                d[x] = index
            elif target == 2 * x:
                l = [d[x], index]
                return l
        
        """
        : If (target-x) also exist in dict and target is not twice value,
        : the result is indexes of x and (target-x)
        """
        for x in nums:
            if ((target-x) in d) and target != 2 * x:
                l = [d[x], d[target-x]]
                return l
posted @ 2016-01-13 20:06  luckysimple  阅读(141)  评论(0编辑  收藏  举报