两数之和
hash表的时间复杂度为什么是O(1)?
hash表是基于数组+链表的实现的。数组在内存中是一块连续的空间,只要知道查找数据的下标就可快速定位到数据的内存地址,即数组查找数据的时间复杂度为O(1)。
能用一次循环解决问题就用一次循环。
class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""has = {}for i in range(len(nums)):key = target - nums[i]if key in has:return i, has[key]has[nums[i]] = i