File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<int> nodesBetweenCriticalPoints(ListNode* head) {
4
+ vector<int>ans = {-1, -1}; // minDist & maxDist
5
+ ListNode* prev = head;
6
+ if(!prev)return ans;
7
+ ListNode* curr = head->next;
8
+ if(!curr)return ans;
9
+ ListNode* nxt = head->next->next;
10
+ if(!nxt)return ans;
11
+
12
+ int firstCp = -1;
13
+ int LastCp = -1;
14
+ int minDis = INT_MAX;
15
+
16
+ int i=1;
17
+ while(nxt){
18
+ bool isCp = ((curr->val > prev->val && curr->val > nxt->val ) ||
19
+ (curr->val < prev->val && curr->val < nxt->val))
20
+ ? true : false;
21
+
22
+ if(isCp && firstCp == -1){
23
+ firstCp = i;
24
+ LastCp = i;
25
+ }
26
+ else if(isCp){
27
+ minDis = min(minDis, i- LastCp);
28
+ LastCp = i;
29
+ }
30
+ ++i;
31
+ prev = prev->next;
32
+ curr = curr->next;
33
+ nxt = nxt->next;;
34
+
35
+ }
36
+ //only One Cp is found
37
+ if(LastCp == firstCp){
38
+ return ans;
39
+ }
40
+ else{
41
+ ans[0] = minDis;
42
+ ans[1] = LastCp - firstCp;
43
+ }
44
+ return ans;
45
+ }
46
+ };
You can’t perform that action at this time.
0 commit comments