1. 程式人生 > >leetcode 852. 山脈陣列的峰頂索引(Peak Index in a Mountain Array)

leetcode 852. 山脈陣列的峰頂索引(Peak Index in a Mountain Array)

我們把符合下列屬性的陣列 A 稱作山脈:

  • A.length >= 3
  • 存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

給定一個確定為山脈的陣列,返回任何滿足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。

示例 1:

輸入:[0,1,0]
輸出:1

示例 2:

輸入:[0,2,1,0]
輸出:
1

提示:

  1. 3 <= A.length <= 10000
  2. 0 <= A[i] <= 10^6
  3. A 是如上定義的山脈

什麼時候應該想到二分呢,有序的陣列,這題通過mid的左右比較判斷單調性,來二分

優秀無bug程式碼

O(n)

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int i = 0;
        while (A[i] < A[i+1]) i++;
        return i;
    }
}

O(logn)

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int lo = 0, hi = A.length - 1;
        while (lo < hi) {
            int mi = lo + (hi - lo) / 2;
            if (A[mi] < A[mi + 1])
                lo = mi + 1;
            else
                hi = mi;
        }
        return lo;
    }
}

下面的程式碼,題目說了長度大於等於3,不然gg,還有如果最值在邊邊也gg

public class 山脈陣列的峰頂索引 {

    public static int peakIndexInMountainArray(int[] A) {
    	int i=0,j=A.length-1;
    	while(i<j) {
    		int mid = i + (j-i)/2;
    		if(A[mid] < A[mid+1])
    			i = mid;
    		else if(A[mid] < A[mid-1])
    			j = mid;
    		else
    			return mid;
    	}
        return i;
    }
    
	public static void main(String[] args) {
		int[] A = new int[] {0,1,3,2};
		System.out.println(peakIndexInMountainArray(A));
	}

}