码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1: Two Sum

时间:2016-01-13 21:31:09      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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):
            if x not in d:
                d[x] = index + 1
            elif target == 2 * x:
                l = [d[x], index+1]
                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

LeetCode 1: Two Sum

标签:

原文地址:http://www.cnblogs.com/luckysimple/p/5128348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!