題目連結 | 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]