我的第一版代码:
def twoSum(self, numbers: list, target): for index, number in enumerate(numbers): tmp = target - number if tmp in numbers: if numbers.index(tmp) == index: continue return [index + 1, numbers.index(tmp) + 1]
其实是没有通过的,主要是没有考虑到数组中有重复元素的情况。突然头脑有一个想法,我们可以先将第一个存起来,然后差值在我们存起来的字典中找存不存在,如果存在就直接返回了!!开搞
def twoSum(self, numbers: list, target): tmp_dic = dict() for index, number in enumerate(numbers): tmp = target - number if tmp in tmp_dic: return [tmp_dic[tmp], index + 1] tmp_dic[number] = index + 1
第二版代码,终于是通过了,貌似有点笨,但是慢慢来吧,从这里发现我需要从不同角度看待一个问题,也许就可以找到一个比较好的解决方法了,找不到解决方法的时候,就不要去想了,不妨先放下,后面再来!