classSolution:deftwoSum(self, nums: List[int], target:int)-> List[int]:
hashmap={
}for i inrange(len(nums)):if hashmap.get(nums[i])isnotNone:return[hashmap.get(nums[i]),i]else:
hashmap[target-nums[i]]= i
2 两数相加
classSolution:defaddTwoNumbers(self, l1: ListNode, l2: ListNode)-> ListNode:
l3_head = ListNode(0)
temp = l3_head
c =0while l1 or l2 or c:
c, value =divmod((l1.val if l1 else0)+(l2.val if l2 else0)+ c,10)
temp.next= ListNode(value)
temp = temp.next
l1 = l1.nextif l1 elseNone
l2 = l2.nextif l2 elseNonereturn l3_head.next
3 无重复字符的最长子串
classSolution:deflengthOfLongestSubstring(self, s:str)->int:
dic ={
}
ml =0
k =-1# 起始下标(不包含)for i inrange(len(s)):if dic.get(s[i])isnotNoneand dic[s[i]]> k:
k = dic[s[i]]
dic[s[i]]= i
ml =max(ml, i-k)return ml
4 寻找两个正序数组的中位数
classSolution:deffindMedianSortedArrays(self, nums1: List[int], nums2: List[int])->float:
len1, len2 =len(nums1),len(nums2)if len1 ==0:return(nums2[(len2+1)//2-1]+ nums2[(len2+2)//2-1])/2if len2 ==0:return(nums1[(len1+1)//2-1]+ nums1[(len1+2)//2-1])/2deffind_kth(nums1, nums2, k):
i, j =0,0whileTrue:
t = k//2# 二分间隔
temp1 =min(i+t, len1)# nums1的第几个数(index+1)
temp2 =min(j+t, len2)# nums2的第几个数(index+1)if nums1[temp1-1]< nums2[temp2-1]:
k -= temp1-i
i = temp1
else: