LeetCode001__TWO SUM

**leetcode 第一题

题目如下:
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.

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

初一看到题目,很简单,双层循环就可以找到那一组数列。

所以很easy啰~
python代码如下

class Solution:
    def twoSum(self, nums, target):
        t=0
        for i in range(0,len(nums)):
            for j in range(i,len(nums)):
                if nums[i]+nums[j]==target and i!=j:
                    return (i,j)

代码通过,结果如下:
双循环结果

嗯,不太满意(废话,这O( N2 )的开销,能好才怪)……
改呗,python提供了字典数据结构,这就是hash的高级应用,改用字典降低时间开销,恩说干就干!

class Solution:
    def twoSum(self, nums, target):
        dict={}
        for i in xrange(len(nums)):
            x=nums[i]
            dict[x]=i
            if target-x in dict:
                return (dict[x],dict[target-x])

看起来很不错了,大大提升时间效率,BTW,结果出问题了:

example:
nums=[5, 22, 3, 2, 7, 16],target=10
结果:(0, 0)

结果不是我们期待的(2, 4)

改改改……
换一下逻辑,又是一个低级错误~~~


class Solution:
    def twoSum(self, nums, target):
        dict={}
        for i in xrange(len(nums)):
            x=nums[i]
            if target-x in dict:
                return (i,dict[target-x])
            dict[x]=i

好了,上OJ
这里写图片描述

还是刚刚达到及格线……不想改了

第一题完成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值