【算法】力扣第 265场周赛

5914. 值相等的最小索引

送分题,数据量也小,才100

class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        for i,n in enumerate(nums):
            if i%10==n:return i
        return -1

一行:

class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        return ([i for i,n in enumerate(nums) if i%10==n]+[-1])[0]

5915. 找出临界点之间的最小和最大距离

连续记录3个结点,为临界点时记录位置(cnt),最后再找一下距离

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
        if not head.next.next:return [-1,-1]
        a,b,c=head,head.next,head.next.next
        res=[]
        cnt=1
        while c:
            if a.val<b.val and c.val<b.val:res.append(cnt)
            if a.val>b.val and c.val>b.val:res.append(cnt)
            a,b,c=b,c,c.next
            cnt+=1
            
        n=len(res)
        if n>=2:
            m2=max(res)-min(res)
            m1=float('inf')
            for i in range(1,n):
                m1=min(m1,res[i]-res[i-1])
            return [m1,m2]
        else:
            return [-1,-1]
        
            

5916. 转化数字的最小运算数

bfs,有3个注意点

  • op运算用lambda生成函数+列表存储
  • deque
  • vis
class Solution:
    def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:
        op1=lambda x,y:x+y
        op2=lambda x,y:x-y
        op3=lambda x,y:x^y
        ops=[op1,op2,op3]
        
        q=deque([(start,0)])
        vis=[0]*1001
        vis[start]=1
        while q:
            x,step=q.popleft()
            for n in nums:
                for op in ops:
                    nx=op(x,n)
                    if nx==goal:
                        return step+1
                    if 0<=nx<=1000 and not vis[nx]:
                        vis[nx]=1
                        q.append((nx,step+1))
        return -1
                    

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>