「LeetCode」第 265 场周赛(上)

175 阅读2分钟

这是我参与11月更文挑战的第9天,活动详情查看2021最后一次更文挑战

链接

leetcode-cn.com/contest/wee…

周赛一共四道题,今天先带来前三道题的解析。

题目

2057. 值相等的最小索引

简单模拟

解析

就是简单模拟,没有什么好说的;顺序遍历每个元素看到哪个的下标满足条件i mod 10 == nums[i]即可;

代码

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

题目

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

简单模拟

解析

严格来说也属于简单模拟的范围。链表题的常规操作是用一个额外prev变量记录之前的那个元素来进行相邻元素值的判断。只需要在这个基础上维护第一个和上一个临界点的位置即可。每次判断出临界点后,更新临界点之间的最大距离(一定会更新)并与上一个临界点距离相减判断最小距离是否需要更新;

代码

# 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]:
        firstCriticalInd, lastCriticalInd, maxGap, minGap = None, None, -1, -1
        lastPoint, p, ind = head, head.next, 1
        if not p:
            return[-1, -1]
        while p.next:
            if p.val < min(lastPoint.val, p.next.val) or p.val > max(lastPoint.val, p.next.val):
                if not firstCriticalInd:
                    firstCriticalInd = ind
                if lastCriticalInd:
                    minGap = min(minGap, ind - lastCriticalInd) if minGap != -1 else ind - lastCriticalInd
                    maxGap = ind - firstCriticalInd
                lastCriticalInd = ind
            lastPoint = p
            p = p.next
            ind += 1
        return [minGap, maxGap]

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

BFS

解析

注意到goal的范围虽然在-10^9和10^9之间,但是求出goal的过程中间的数只会在0到1000之间。用一个数组维护0到1000这1001个所有的“过程数”是否出现过,然后对每个步骤的三个结果数当作下一个步骤的操作数用BFS,即可得出最少操作步骤。

本质上这和图的BFS遍历过程是一致的,节点为0~1000这1001个节点,但要考虑可能出现在这个范围外的goal

代码

class Solution:
    def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:
        countList = [-1] * 1001
        countList[start] = 0
        queue = []
        queue.append(start)
        time = 0
        while len(queue) > 0:
            eleCount = len(queue)
            time += 1
            for i in range(0, eleCount):
                firstEle = queue.pop(0)
                for num in nums:
                    plusEle = firstEle + num
                    minusEle = firstEle - num
                    xorEle = firstEle ^ num
                    if plusEle == goal or minusEle == goal or xorEle == goal:
                        return time
                    if 0 <= plusEle <= 1000 and countList[plusEle] == -1:
                        countList[plusEle] = time
                        queue.append(plusEle)
                    if 0 <= minusEle <= 1000 and countList[minusEle] == -1:
                        countList[minusEle] = time
                        queue.append(minusEle)
                    if 0 <= xorEle <= 1000 and countList[xorEle] == -1:
                        countList[xorEle] = time
                        queue.append(xorEle)
        return -1