/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int> nodesBetweenCriticalPoints(ListNode* head)
{
vector<int> res = {-1, -1};
int minDist = INT_MAX;
ListNode* prev = head;
ListNode* cur = head->next;
int i = 1;
int last = 0;
int first = 0;
while (cur->next)
{
// if (localMinimum || localMaximum)
if ((cur->val < prev->val && cur->val < cur->next->val) || (cur->val > prev->val && cur->val > cur->next->val))
{
// 如果這是第一個 critial point,則將 last 和 first 都設為當前的 index i。
if (last == 0)
{
last = i;
first = i;
}
else
{
minDist = min(minDist, i - last);
// 更新 last critial point
last = i;
}
}
i++;
// update the pointer
prev = cur;
cur = cur->next;
}
if (minDist != INT_MAX)
{
// maxDist 即為 last - first
int maxDist = last - first;
res = {minDist, maxDist};
}
return res;
}
};
- T: O(N)
- S: O(1)