题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个长度至少为二的链表,其中可能存在局部的极大点或者极小点,返回极值点之间的最小距离和最大距离

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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]:
first, last = 0, 0
a, b, c = head, head.next, head.next.next
index = 1
minDist = inf
while c:
if a.val < b.val > c.val or a.val > b.val < c.val:
if first == 0:
first = index
if last > 0 and index-last < minDist:
minDist = index-last
last = index
a, b, c = b, c, c.next
index += 1
return [minDist, last-first] if first != last else [-1, -1]