记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
l记录每个单词长度
s记录每个单词内所含字符
如果s[i] s[j]相交为空 说明单词word[i] word[j]不含相同字符
def maxProduct(words):
"""
:type words: List[str]
:rtype: int
"""
s = []
l = []
maxl = 0
for word in words:
l.append(len(word))
maxl = max(maxl,len(word))
s.append(set(word))
n = len(words)
ans = 0
for i in range(n-1):
for j in range(i,n):
if l[i]*maxl<ans:
break
if not s[i]&s[j]:
ans = max(ans,l[i]*l[j])
return ans
依次判断
def vowelStrings(words, left, right):
"""
:type words: List[str]
:type left: int
:type right: int
:rtype: int
"""
s=set({'a','e','i','o','u'})
ans = 0
for i in range(left,right+1):
w=words[i]
if w[0] in s and w[len(w)-1] in s:
ans+=1
return ans
从头遍历记录连续0或1的个数
def findTheLongestBalancedSubstring(s):
"""
:type s: str
:rtype: int
"""
ans = 0
if len(s)==0:
return ans
one = 0
zero = 0
pre = 0
for c in s:
if c=='0':
pre = 0
one = 0
zero+=1
else:
pre = max(pre,zero)
zero = 0
one +=1
ans = max(ans,2*min(pre,one))
ans = max(ans,2*min(pre,one))
return ans
计算人到安全屋时间 以及安全屋隔壁的时间
火到安全屋的时间
判断人是否能比火先到安全屋的隔壁
def maximumMinutes(grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m,n=len(grid),len(grid[0])
def bfs(l):
t = [[-1]*n for _ in range(m)]
for i,j in l:
t[i][j]=0
cur = 1
while l:
tmp = []
for i,j in l:
for x,y in (i-1,j),(i,j-1),(i+1,j),(i,j+1):
if 0<=x<m and 0<=y<n and grid[x][y]==0 and t[x][y]<0:
t[x][y] = cur
tmp.append((x,y))
cur+=1
l=tmp
return t[-1][-1],t[-1][-2],t[-2][-1]
m0,m1,m2=bfs([(0,0)])
if m0<0:
return -1
fire = [(i,j) for i,g in enumerate(grid) for j,x in enumerate(g) if x==1]
f0,f1,f2 = bfs(fire)
if f0<0:
return 10**9
d = f0-m0
if d<0:
return -1
if m1!=-1 and m1+d<f1 or (m2!=-1 and m2+d<f2):
return d
return d-1
将药水强度从小到大排序
二分查找 咒语能够成功匹配的药水强度的位置
def successfulPairs(spells, potions, success):
"""
:type spells: List[int]
:type potions: List[int]
:type success: int
:rtype: List[int]
"""
n = len(potions)
potions.sort()
ans = []
for s in spells:
v = (success+s-1)//s
l,r=0,n-1
while l<r:
mid = (l+r)//2
if potions[mid]<v:
l = mid+1
else:
r = mid
if s*potions[r]>=success:
ans.append(n-r)
else:
ans.append(0)
return ans
如果有k对情侣坐错 需要交换k-1次
并查集将坐错的情侣分区
def minSwapsCouples(row):
"""
:type row: List[int]
:rtype: int
"""
def find(pre,x):
if pre[x]!=x:
pre[x] = find(pre,pre[x])
return pre[x]
n = len(row)
pre = list(range(n//2))
num = [1]*(n//2)
for i in range(0,n,2):
x = find(pre,row[i]//2)
y = find(pre,row[i+1]//2)
if x!=y:
pre[x]=y
num[y]+=num[x]
ans = 0
for i in range(n//2):
if pre[i]==i:
ans += num[i]-1
return ans