0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #852: Peak Index in a Mountain Array

Last updated at Posted at 2019-07-31

Solution 1: Intuitive

func peakIndexInMountainArray(_ A: [Int]) -> Int {
    for i in stride(from: 1, to: A.count, by: 1) {
        if A[i] < A[i-1] {
            return i-1
        }
    }
    return -1
}

Solution 2: Binary Search

func peakIndexInMountainArray(_ A: [Int]) -> Int {
    var start = 0
    var end = A.count - 1
    while start < end {
        let mid = start + (end - start) / 2
        if A[mid] < A[mid+1] {
            start = mid + 1
        } else {
            end = mid
        }
    }
    return start
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?