记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
- 12/23 1847. 最近的房间
- 12/24 3291. 形成目标字符串需要的最少字符串数 I
- 12/25 3292. 形成目标字符串需要的最少字符串数 II
- 12/26 3083. 字符串及其反转中是否存在同一子字符串
- 12/27 3159. 查询数组中元素的出现位置
- 12/28 3046. 分割数组
- 12/29
12/23 1847. 最近的房间
经房间按大小排序
先考虑minSize大的查询
将比minSize大的房间号放入ids序列中考虑
根据当前查询preferred_id 在ids中查找离他最近的两个id 比较差值大小
def closestRoom(rooms, queries):
"""
:type rooms: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
from sortedcontainers import SortedList
n=len(rooms)
rooms.sort(key=lambda x:x[1])
m=len(queries)
ans=[-1]*m
ids=SortedList()
j=n-1
for i in sorted(range(m),key=lambda i:-queries[i][1]):
pid,msize=queries[i]
while j>=0 and rooms[j][1]>=msize:
ids.add(rooms[j][0])
j-=1
diff=float("inf")
k = ids.bisect_left(pid)
if k:
diff = pid-ids[k-1]
ans[i]=ids[k-1]
if k<len(ids) and ids[k]-pid<diff:
ans[i]=ids[k]
return ans
12/24 3291. 形成目标字符串需要的最少字符串数 I
对于每个word 与target求出在结束在target[i]的前缀能够匹配的最长前缀back[i]
动态规划 dp[i]表示前i个字母需要最少字符串数
def minValidStrings(words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
def prefix(word,target):
s=word+"#"+target
n=len(s)
pi=[0]*n
for i in range(1,n):
j=pi[i-1]
while j>0 and s[i]!=s[j]:
j=pi[j-1]
if s[i]==s[j]:
j+=1
pi[i]=j
return pi
n=len(target)
back = [0]*n
for w in words:
pi = prefix(w, target)
m=len(w)
for i in range(n):
back[i]=max(back[i],pi[m+1+i])
dp=[0]+[10**9]*n
for i in range(n):
dp[i+1]=dp[i+1-back[i]]+1
if dp[i+1]>n:
return -1
return dp[n]
12/25 3292. 形成目标字符串需要的最少字符串数 II
对于每个word 与target求出在结束在target[i]的前缀能够匹配的最长前缀back[i]
动态规划 dp[i]表示前i个字母需要最少字符串数
def minValidStrings(words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
def prefix(word,target):
s=word+"#"+target
n=len(s)
pi=[0]*n
for i in range(1,n):
j=pi[i-1]
while j>0 and s[i]!=s[j]:
j=pi[j-1]
if s[i]==s[j]:
j+=1
pi[i]=j
return pi
n=len(target)
back = [0]*n
for w in words:
pi = prefix(w, target)
m=len(w)
for i in range(n):
back[i]=max(back[i],pi[m+1+i])
dp=[0]+[10**9]*n
for i in range(n):
dp[i+1]=dp[i+1-back[i]]+1
if dp[i+1]>n:
return -1
return dp[n]
12/26 3083. 字符串及其反转中是否存在同一子字符串
map记录所有长度为2的子字符串
如果某个子字符串倒序也在map中 返回true
def isSubstringPresent(s):
"""
:type s: str
:rtype: bool
"""
m={}
for i in range(len(s)-1):
m[s[i:i+2]]=1
if s[i:i+2][::-1] in m:
return True
return False
12/27 3159. 查询数组中元素的出现位置
遍历一边nums记录x的位置
def occurrencesOfElement(nums, queries, x):
"""
:type nums: List[int]
:type queries: List[int]
:type x: int
:rtype: List[int]
"""
cur=1
m={}
for i,v in enumerate(nums):
if v==x:
m[cur]=i
cur+=1
n=len(queries)
ans=[-1]*n
for i,v in enumerate(queries):
if v in m:
ans[i]=m[i]
return ans
12/28 3046. 分割数组
统计每个数的出现次数 如果次数超过2则无法按要求分割
def isPossibleToSplit(nums):
"""
:type nums: List[int]
:rtype: bool
"""
m={}
for num in nums:
m[num]=m.get(num,0)+1
if m[num]>2:
return False
return True
12/29