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

题目链接 2058. 找出临界点之间的最小和最大距离
思路 模拟
题解链接 一次遍历 + 常数空间
关键点
时间复杂度 \(O(n)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
        min_dist = max_dist = -1
        first = last = -1
        
        pos = 0
        cur = head
        while cur.next.next:
            x, y, z = cur.val, cur.next.val, cur.next.next.val
            if y > max(x, z) or y < min(x, z):
                if last != -1:
                    dist = pos - last
                    if min_dist == -1:
                        min_dist = dist
                    else:
                        min_dist = min(min_dist, dist)
                    max_dist = max(dist, pos - first)
                if first == -1:
                    first = pos
                last = pos
            pos += 1
            cur = cur.next
        return [min_dist, max_dist]
posted @ 2024-09-11 00:07  WrRan  阅读(5)  评论(0编辑  收藏  举报