题目链接 | 2058. 找出临界点之间的最小和最大距离 |
---|---|
思路 | 模拟 |
题解链接 | 一次遍历 + 常数空间 |
关键点 | 无 |
时间复杂度 | \(O(n)\) |
空间复杂度 | \(O(1)\) |
代码实现:
class Solution:def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:min_dist = max_dist = -1first = last = -1pos = 0cur = headwhile cur.next.next:x, y, z = cur.val, cur.next.val, cur.next.next.valif y > max(x, z) or y < min(x, z):if last != -1:dist = pos - lastif min_dist == -1:min_dist = distelse:min_dist = min(min_dist, dist)max_dist = max(dist, pos - first)if first == -1:first = poslast = pospos += 1cur = cur.nextreturn [min_dist, max_dist]