image.png

思路

顺序遍历

  1. public int peakIndexInMountainArray(int[] A) {
  2. for(int i=1;i<A.length-1;i++){
  3. if(A[i]>A[i+1])
  4. return i;
  5. }
  6. return 0;
  7. }

二分查找

  1. public int peakIndexInMountainArray(int[] A) {
  2. int low = 0;
  3. int high = A.length-1;
  4. while(low<=high){
  5. int mid = low + ((high-low)>>1);
  6. if(A[mid]>A[mid+1]&&A[mid]>A[mid-1]){
  7. return mid;
  8. }else if(A[mid]<A[mid+1]&&A[mid]>A[mid-1])
  9. low = mid+1;
  10. else
  11. high = mid -1;
  12. }
  13. return -1;
  14. }