[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的情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值