3.无重复字符的最长子串
解题思路:
- 使用map的滑动窗口解法,和第二题使用hashmap优化类似
- 滑动窗口法的思想是,在ans上设置一个start和end指针,end指针随着字符存入而改变,start指针随着出现重复元素而改变
- 判断新进入的字符串是否存在于之前的map中,若存在,则移动start指针到map中重复元素的位置
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
ans = start = 0
map = {}
for end,val in enumerate(s): #end是提取字符串s中元素的位置
if val in map.keys():
start = max(map.get(val)+1,start) #这里的+1是将指针后移,删除开头的重复元素
map[val] = end #将字符和end存入map
ans = max(ans,end-start+1)
return ans
特殊情况:
- 字符串为空
- 字符串全部为相同字符
4.寻找两个正序数组的中位数
这个题我想的是合并nums1和nums2,排序后根据length是单数还是双数找到中位数。
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
#num = nums1.append(nums2)
numss = nums1 + nums2
num = sorted(numss)
n = len(num)
if n%2==0:
ans = 0.5*(num[(n/2)-1]+num[n/2])
elif n%2 ==1:
ans = num[(n-1)/2]
return ans