[Lintcode]56. Two Sum

56. Two Sum

Description

  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 zero-based.

Example
numbers=[2, 7, 11, 15], target=9

return [0, 1]

Challenge
Either of the following solutions are acceptable:

O(n) Space, O(nlogn) Time
O(n) Space, O(n) Time
Notice
You may assume that each input would have exactly one solution

我的代码

class Solution:
    """
    @param numbers: An array of Integer
    @param target: target = numbers[index1] + numbers[index2]
    @return: [index1, index2] (index1 < index2)
    """
    def twoSum(self, nums, target):
        # write your code here
        for i in range(len(nums)):
            if 2*nums[i] == target:
                nums[i] += 1
                try:
                    return [i, nums.index(target - nums[i]+1)]
                except:
                    nums[i] -= 1
                    continue
            try:
                return [i,nums.index(target-nums[i])]
            except:
                continue

法二

def twoSum(self, nums, target):
    # write your code here
    res = {}
    for i,item in enumerate(nums):
        if target - item in res.keys():
            return [res[target-item],i]
        else:
            res[item] = i

思路:

1.之前没考虑target/2的情况
2.没考虑两个相同的数字的情况,就很野蛮地直接排除了target/2的情况,结果少了[3,3] 6的情况
3.list 的index的时间复杂度是O(n),所以这个的时间复杂度是O(n^2), 用dict查询的话,利用的是hash table,理想情况下,时间复杂度是O(1),整体时间复杂度是O(n).

法二更简单。不用考虑target/2的情况

posted @ 2019-01-07 21:32  siriusli  阅读(113)  评论(0编辑  收藏  举报