leetcode (Peak Index in a Mountain Array)
阿新 • • 發佈:2019-01-10
Title:Peak Index in a Mountain Array 852
Difficulty:Easy
原題leetcode地址: https://leetcode.com/problems/peak-index-in-a-mountain-array/
1. 二分法
時間複雜度:O(logn),一層while迴圈。
空間複雜度:O(1),沒有申請額外空間。
/** * 二分法 * @param A * @return */ public static int peakIndexInMountainArray(int[] A) { int low = 0; int high = A.length - 1; while (low <= high) { int mid = (low + high) / 2; if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) { return mid; } else if (A[mid] > A[mid - 1] && A[mid] < A[mid + 1]) { low = mid + 1; } else { high = mid - 1; } } return -1; }