1. 两数之和 (python)

一. 题目

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

二.思路

1)自己思路

1> 双指针遍历数组

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if nums == []:
            return None
        else:
            i = 0
            
            while i < len(nums) - 1:
                j = i + 1
                while j < len(nums):
                    if nums[i] + nums[j] == target:
                        return i,j
                    else:
                        j += 1
                i += 1

这个方法,如果加上前面的空集判定,会超时。 

2)参考思路

1> hash table:思路是用dict构建hash table:以给定数组的值为hash table 的key,给定数组的index为给定数组的value。

好处是不需要循环就能直接返回指定value的index,也就是比较快的查找。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """        
        hash_dict = {}
        for i, v in enumerate(nums):
            hash_dict[v] = i
        for i2, v2 in enumerate(nums):
            if target-v2 in hash_dict and hash_dict[target-v2] != i2:
                return [i2, hash_dict[target-i2]]

key和value的指定需要具体问题具体分析。emm,是不是一般要return什么就把什么当作字典的value呢?

2> hash table的法2

不需要提前构建好hash table,而是边循环边构建边判断

大概思路是从首位开始将数组中的每个项需要寻找的值(也就是 target -v)为k,和这个项的index为v放入hash字典里。 如果数组后续的值有与这个需要寻找的值相等的情况,那么这个数组的值的index和需要寻找的值的index上的数加起来就是target。

emm...通俗来讲就是,数组的每一项提出了需求说:我就要找这个数。然后列了个表,如果后续有相等,就是找到了。

也就是 [将需求放入字典里,如果后续的值满足这个需求,那么就接着操作]

  class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """      

        hash_dict = {}
        for i, v in enumerate(nums):
            if v in hash_dict:
                return [i, hash_dict[v]]
            else:
                hash_dict[target - v] = i

优点:只遍历一遍数组 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值