2058. Find the Minimum and Maximum Number of Nodes Between Critical Points 解題紀錄

A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].   Example 1:
megapx
Input: head = [3,1] Output: [-1,-1] Explanation: There are no critical points in [3,1]. Example 2:
megapx
Input: head = [5,3,1,2,5,1,2] Output: [1,3] Explanation: There are three critical points: - [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. - [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. - [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. Example 3:
megapx
Input: head = [1,3,2,2,3,2,2,2,7] Output: [3,3] Explanation: There are two critical points: - [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. - [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. Both the minimum and maximum distances are between the second and the fifth node. Thus, minDistance and maxDistance is 5 - 2 = 3. Note that the last node is not considered a local maxima because it does not have a next node.   Constraints: The number of nodes in the list is in the range [2, 10^5]. 1 <= Node.val <= 10^5 今天這題給我們一個 linked list 的頭, 希望我們找到極大或極小值,並從這些極大極小值找出最近及最遠相鄰距離。 極大極小值一定要被前後 node 包裹,不能是頭或尾, 而且要注意相鄰距離不能用同一個極大極小值, 就代表我們至少要找到兩個極值才能回傳答案, 否則就要回傳 {-1, -1}。 這題應該只要注意那個就好, 其他就是設變數還有微分斜率相乘做判斷(複習:離散的微分是相鄰元素相減(#))。 C++程式碼:
megapx
假設 head 是一條包含 N 個 node 的 head。 計算複雜度:O(N) 空間複雜度:O(1) Github程式碼:
MrMur:這題我 2024年就寫過,現在回頭看程式碼風格迥異,且看不太懂當初自己為什麼邏輯要那麼複雜? 有興趣的可以 github同資料夾看看,每天刷題刷兩年的差異(#。
愛心
101
2
全部留言
浪跡,有什麼簡易的image比對工具
sticker
你要比對哪種 image?