hot100 -- 1.哈希系列
1.两数之和
题目:
给定一个字符串 s
,请你找出其中不含有重复字符的 最长 子串 的长度。
题解:
方法1:暴力求解
def get_two_sum(nums, target):for i in range(len(nums)):for j in range(i+1, len(nums)):if nums[i] + nums[j] == target:return [i, j]
方法2:哈希表+排序+双指针
import collections
def get_two_sum(nums, target):hash = collections.defaultdict(list)# 用哈希表记录位置for i in range(len(nums)):# if nums[i] not in hash:hash[nums[i]].append(i)print(hash)nums.sort()# 双指针寻找left, right = 0, len(nums) - 1while left < right:if nums[left] + nums[right] == target:return [hash[nums[left]].pop(), hash[nums[right]].pop()]elif nums[left] + nums[right] > target:right -= 1else:left += 1
方法3:哈希表(补数)
def get_two_sum(nums, target):hash = {}for i in range(len(nums)):# 找到补数,直接返回if target - nums[i] in hash:return [hash[target - nums[i]], i]hash[nums[i]] = i