链接: 6225. 差值数组不同的字符串
按题意模拟。
class Solution:
def oddString(self, words: List[str]) -> str:
m,n = len(words),len(words[0])
ans = 0
for i in range(n-1):
s = defaultdict(list)
for j in range(m):
y = ord(words[j][i]) - ord(words[j][i+1])
s[y].append(j)
# print(s)
if len(s)>1:
for k,v in s.items():
if len(v)==1:
return words[v[0]]
class Solution:
def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:
# 1072 ms
# d = set(dictionary) # 储存dic和dic每个单词枚举每个字符变*,最多共2*n个元素
# n = len(queries[0])
# for s in dictionary: # 复杂度n*n
# p = list(s)
# for i in range(n):
# t = p[i]
# p[i]='*'
# d.add(''.join(p))
# p[i]=t
# def calc_dis(a,b): # 计算a和b的距离,复杂度n
# d = 0
# for x, y in zip(a,b):
# if x == y or y == '*':
# continue
# d += 1
# if d>=2: # 2以上都没用,提前返回
# return d
# return d
# def calc_min_dis_less_than_2(s): # 查询是否存在一个目标元素的编辑距离距s小于2(最大是1)
# for b in d:
# if calc_dis(s,b)<2:
# return True
# return False
# return [q for q in queries if calc_min_dis_less_than_2(q)]
def calc_dis(a,b):
d = 0
for x,y in zip(a,b):
if x == y:
continue
d += 1
if d >=3:
return d
return d
def calc_min_dis_less_than_3(s):
for b in dictionary:
if calc_dis(s,b) < 3:
return True
return False
return [q for q in queries if calc_min_dis_less_than_3(q)]
链接: 6226. 摧毁一系列目标
class Solution:
def destroyTargets(self, nums: List[int], space: int) -> int:
d = defaultdict(list)
for x in nums:
d[x%space].append(x)
mx = 0
ans = inf
for k,v in d.items():
if len(v)>mx:
mx = len(v)
ans = min(v)
elif len(v) == mx:
ans = min(ans,min(v))
return ans
链接: 6227. 下一个更大元素 IV
class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [-1]*n
a = sorted(zip(nums,range(n)),reverse=True)
from sortedcontainers import SortedList
h = SortedList()
t = deque()
for x,i in a:
while t and t[0][0] != x:
h.add(t.popleft()[1])
p = h.bisect_left(i)
if p + 1 <len(h):
ans[i] = nums[h[p+1]]
t.append((x,i))
return ans
单调栈
class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [-1]*n
s,t = [],[]
for i,v in enumerate(nums):
while t and nums[t[-1]] < v:
ans[t.pop()] = v
x = []
while s and nums[s[-1]] < v:
x.append(s.pop())
t += x[::-1]
s.append(i)
return ans