记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
- 5/20 1542. 找出最长的超赞子字符串
- 5/21 2769. 找出最大的可达成数字
- 5/22 2225. 找出输掉零场或一场比赛的玩家
- 5/23 2831. 找出最长等值子数组
- 5/24 1673. 找出最具竞争力的子序列
- 5/25 2903. 找出满足差值条件的下标 I
- 5/26
5/20 1542. 找出最长的超赞子字符串
要组成回文串
如果字符串个数为偶数 所有字符出现次数都要为偶数次
如果字符串个数为奇数 只有一个字符出现次数为奇数次
使用异或前缀和mask=pre[i] 来记录字符串s[:i]中数字出现的奇偶性
对于某个子字符串i:j 只需pre[i]^pre[j]
使用map记录所有mask第一次出现的位置
def longestAwesome(s):""":type s: str:rtype: int"""n=len(s)pos = [n]*(1<<10)pos[0]=-1ans = 0pre = 0for i,x in enumerate(map(int,s)):pre ^= 1<<xans = max(ans,i-pos[pre],max(i-pos[pre^(1<<d)] for d in range(10)))if pos[pre]==n:pos[pre]=ireturn ans
5/21 2769. 找出最大的可达成数字
可达数字尽可能大
那么需要t此操作 num每次增1 可达数字每次减1
即num+2*t
def theMaximumAchievableX(num, t):""":type num: int:type t: int:rtype: int"""return num+2*t
5/22 2225. 找出输掉零场或一场比赛的玩家
zero存储没有输掉比赛的玩家 one存储输掉了一场的玩家
other存储输掉超过一场的玩家
def findWinners(matches):""":type matches: List[List[int]]:rtype: List[List[int]]"""zero,one=set(),set()other = set()for w,l in matches:if w not in other and w not in one:zero.add(w)if l in zero:zero.remove(l)one.add(l)elif l in one:one.remove(l)other.add(l)elif l not in other:one.add(l)return [sorted(list(zero)),sorted(list(one))]
5/23 2831. 找出最长等值子数组
将相同的数值坐标放入一个数组pos中
在该数组中滑动窗口 判断相同数值最多能有几个相连
对于pos[l] pos[r]中间的情况需要删除
子数组长度为pos[r]-pos[l]+1
相同的有r-l+1个
所以需要删掉的数为 pos[r]-pos[l]-(r-l)
def longestEqualSubarray(nums, k):""":type nums: List[int]:type k: int:rtype: int"""from collections import defaultdictpos = defaultdict(list)for i,num in enumerate(nums):pos[num].append(i)ans = 0for cur in pos.values():if len(cur)<=ans:continuel = 0for r in range(len(cur)):while cur[r]-cur[l]-(r-l)>k:l+=1ans = max(ans,r-l+1)return ans
5/24 1673. 找出最具竞争力的子序列
从头遍历 用一个栈来存储当前序列
如果当前值x小于栈顶的值 且 弹出栈顶的值加上剩余元素能够大于k则弹出
如果栈的大小小于k 则x入栈
def mostCompetitive(nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""st=[]for i,x in enumerate(nums):while st and x<st[-1] and len(st)+len(nums)-i>k:st.pop()if len(st)<k:st.append(x)return st
5/25 2903. 找出满足差值条件的下标 I
个数小于100个 双层循环遍历
def findIndices(nums, indexDifference, valueDifference):""":type nums: List[int]:type indexDifference: int:type valueDifference: int:rtype: List[int]"""n=len(nums)for i in range(n-indexDifference):for j in range(i+indexDifference,n):if abs(nums[i]-nums[j])>=valueDifference:return [i,j]return [-1,-1]
5/26