思路:
双指针+滑动窗口
模板:求最长子集
class Solution(object):
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
n = len(s)
ans = 0
#统计字符数量
counter = collections.Counter()
left = 0
right = 0
while right < n:
#统计字符数量
counter[s[right]] += 1
#左指针滑动条件,通常是不符合哪些情况
while right -left + 1 - counter.most_common()[0][1] > k:
counter[s[left]] -= 1
left += 1
ans = max(ans,right - left + 1)
right += 1
return ans
本题:输入格式自己去写吧,直接调用函数即可
import collections
def function(numList:List[int],nums) -> int:
n = len(numList)
counter = collections.Counter()
left = 0
right = 0
ans = 0
pos = []
while right < n:
counter[numList[right]] += 1
while counter[-nums] > 0 or right - left + 1 - counter[nums] > 1:
counter[numList[left]] -= 1
left += 1
if ans < right-left + 1:
ans = right - left + 1
for i,x in enumerate(numList[left:right + 1]):
if x == 0:
pos = [left + i]
elif ans == right - left + 1:
for i, x in enumerate(numList[left:right + 1]):
if x == 0:
pos.append(left + i)
right += 1
mid = (n-1)//2
pos.sort(key=lambda x : abs(x - mid))
return pos[0]
numsList = [-1,0,1,1,1,0,1,-1,1]
# numsList = [0,0,0,0,1,0,0,0,0,1,0]
print(function(numsList,-1))