/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func nodesBetweenCriticalPoints(head *ListNode) []int {
a, b, c := head, head.Next, head.Next.Next
first, last, minDis := 0, 0, math.MaxInt32
for i, prev := 1, 0; c != nil; i++ { // 遍历链表,寻找临界点
if a.Val < b.Val && b.Val > c.Val || a.Val > b.Val && b.Val < c.Val {
if first == 0 {
first = i // 首个临界点位置
}
last = i // 最末临界点位置
if prev > 0 && i-prev < minDis {
minDis = i - prev // 更新相邻临界点位置之差的最小值
}
prev = i
}
a, b, c = b, c, c.Next
}
if first == last { // 临界点少于两个
return []int{-1, -1}
}
return []int{minDis, last - first}
}
# 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]:
minDist = maxDist = -1
first = last = -1
pos = 0
cur = head
while cur.next.next:
# 获取连续的三个节点的值
x, y, z = cur.val, cur.next.val, cur.next.next.val
# 如果 y 是临界点
if y > max(x, z) or y < min(x, z):
if last != -1:
# 用相邻临界点的距离更新最小值
minDist = (pos - last if minDist == -1 else min(minDist, pos - last))
# 用到第一个临界点的距离更新最大值
maxDist = max(maxDist, pos - first)
if first == -1:
first = pos
# 更新上一个临界点
last = pos
cur = cur.next
pos += 1
return [minDist, maxDist]