开始刷 LeetCode,争取一个月内刷完
加油,加油,加油
今天太迟了,就刷一道吧。。。
1. 问题描述
2. 解法
比较容易想到的就是暴力解决即在双重循环,在每一个值下遍历寻找target - 该值,O(n^2)
还用种就是哈希表,python中就是字典
class Solution: @staticmethod def two_num(nums, target): dic = {} for index, num in enumerate(nums): if num > target: continue else: _num = target - num # 不能重复数值 if _num == num: continue else: if _num in dic: return [dic[_num], index] dic[num] = index @staticmethod def two_num_2(nums, target): dic = {} for index, num in enumerate(nums): # 其实可能会有负数,所以不是 > 就要跳过 # 不能重复数值(题目写着不能重复使用,结果测试给了个【3,3】,6。。。) _num = target - num if _num in dic: return [dic[_num], index] dic[num] = index @staticmethod def two_num_3(nums, target): dic = {} for index, num in enumerate(nums): _num = target - num try: temp = dic[_num] except KeyError: dic[num] = index else: return [temp, index]