题目链接:力扣
思路:用三个指针标记三个位置,从前往后找满足条件的小标,放在数组里面,最大距离好找,就是数组中最后一个和第一个的差,最小距离就是数组中相邻的两个值的差的最小值(最下距离,在循环的时候判断一下即可,这是一个坑点)~~
上代码:
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun nodesBetweenCriticalPoints(head: ListNode?): IntArray {
val arrayIndex = ArrayList<Int>()
var front = head
var behind = head?.next
var index = 1
var minn = 1000000
while (behind?.next != null) {
val p = behind.next
if (front?.`val`!! < behind.`val` && behind.`val` > p?.`val`!!
|| front.`val` > behind.`val` && behind.`val` < p?.`val`!!) {
arrayIndex.add(index)
if (arrayIndex.size > 1) {
minn = minn.coerceAtMost(arrayIndex[arrayIndex.size - 1] - arrayIndex[arrayIndex.size - 2])
}
}
front = behind
behind = p
index++
}
if (arrayIndex.size > 1) {
return intArrayOf(minn, arrayIndex[arrayIndex.size - 1] - arrayIndex[0])
}
return intArrayOf(-1, -1)
}
}