LeetCode之Peak Index in a Mountain Array(Kotlin)

问题:
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].


方法:
遍历数组,找到山峰所在的index输出即可。

具体实现:

class PeakIndexInAMountainArray {
    fun peakIndexInMountainArray(A: IntArray): Int {
        var peakIndex = 0
        for (i in A.indices) {
            if (A[i] > A[peakIndex]) {
                peakIndex = i
            }
        }
        return peakIndex
    }
}

fun main(args: Array) {
    val array = intArrayOf(0,1,0)
    val peakIndexInAMountainArray = PeakIndexInAMountainArray()
    println("result: ${peakIndexInAMountainArray.peakIndexInMountainArray(array)}")
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Peak Index in a Mountain Array(Kotlin))