leetcode0-HASH搜索

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

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

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

first try:循环开始指定双起点,不满足则第二起点前进,再次循环,很大重复工作
result:time out
test example :19/20

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        rlist = []
        # nums = []
        # print(len(nums))
        n = len(nums) 
        n >=0
        a = 0
        b = 1
        while True:
            if nums[a]+nums[b] == target:
                rlist.append(a)
                rlist.append(b)
                return rlist
            else:
                if b < n-1:
                    b += 1
                    continue
                else:
                    a += 1
                    b = a+1
                    continue

2nd try:HASH散列在python中的应用--dict,这样就是O(n)
结果:time out 错误在一个keyerror:62
第二次尝试又把python的字典操作复习了一遍
python繁琐工作自动化
python优雅的操作字典:https://www.linuxzen.com/python-you-ya-de-cao-zuo-zi-dian.html

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        rlist = []
        rdict = {}
        n = len(nums)
        for i in nums :
            rdict[nums.index(i)] = i
        print(rdict)
        a = 0
        values = rdict.values()
        while True:
            want = target - rdict[a]
            if want in values:
                print(want)
                ri = {v:k for k,v in rdict.items()}
                rlist.append(a)
                rlist.append(ri[want])
                return rlist
            else:
                a+=1
                continue

keyerror用try-except做了异常处理
随后因为超时原因又做了修改,即 把反向字典的构造放在最开始
结果在处理[3,3]时出现错误,因为字典构造时尊重key的唯一性,造成相同值的覆盖

for i in nums :
    rdict[nums.index(i)] = i
print(rdict)    # 结果不是{3:0,3:1}而是{3:0}

你可能感兴趣的:(leetcode0-HASH搜索)