-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodesBetweenCriticalPoints2058.java
67 lines (58 loc) · 2.29 KB
/
NodesBetweenCriticalPoints2058.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
public class NodesBetweenCriticalPoints2058 {
/*
* 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] .
*
*/
public class ListNode {
int val ;
ListNode next ;
ListNode(){};
ListNode( int val) {this.val= val ;} ;
ListNode (int val , ListNode next) {
this.next = next ;
this.val = val ;
}
}
class Solution {
public int[] nodesBetweenCriticalPoints(ListNode head) {
int ans [] = {-1 , -1} ;
ListNode pre = head;
int min = Integer.MAX_VALUE ;
ListNode curr = head.next ;
int currIdx = 1 ;
int preIdx = 0 ;
int initIdx = 0 ;
while (curr.next != null){
if ((pre.val < curr.val && curr.next.val < curr.val )||(pre.val > curr.val && curr.next.val > curr.val)){
if (preIdx == 0 ) {
initIdx = currIdx ;
preIdx = currIdx ;
}
else {
min = Math.min(min, currIdx - preIdx) ;
preIdx = currIdx ;
}
}
currIdx++;
pre = curr ;
curr = curr.next ;
}
if (min != Integer.MAX_VALUE) {
ans = new int[]{min , preIdx - initIdx} ;
}
return ans;
}
}
}