congr / world

2 stars 1 forks source link

LeetCode : 852. Peak Index in a Mountain Array #428

Open congr opened 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/peak-index-in-a-mountain-array/ image

congr commented 5 years ago

331

Similar question

congr commented 5 years ago

AC, faster than 2%. ( slowest)

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        for (int i = 1; i < A.length - 1; i++) {
            if (A[i-1] < A[i] && A[i] > A[i+1]) return i;
        }
        return -1;
    }
}
congr commented 5 years ago

Runtime: 2 ms, faster than 75.92% of Java online submissions for Peak Index in a Mountain Array.

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int s = 0, e = A.length -1;

        while(s<e) {
            int m = (s+e)/2;

            if (A[m] > A[m+1]) e=m;
            else s = m + 1;
        }

        return s;
    }
}