Let's call an array arr a mountain if the following properties hold:
- arr.length >= 3
- There exists some i with 0 < i < arr.length - 1 such that:
- arr[0] < arr[1] < ... arr[i-1] < arr[i]
- arr[i] > arr[i+1] > ... > arr[arr.length - 1]
Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
Example 1:
Input: arr = [0,1,0]
Output: 1
Example 2:
Input: arr = [0,2,1,0]
Output: 1
Example 3:
Input: arr = [0,10,5,2]
Output: 1
Constraints:
- 3 <= arr.length <= 104
- 0 <= arr[i] <= 106
- arr is guaranteed to be a mountain array.
Solution:
class Solution {
public int peakIndexInMountainArray(int[] A) {
int lo = 0, hi = A.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (A[mid] < A[mid + 1]) {
// peak index is after mid.
lo = mid + 1;
}else if (A[mid -1] > A[mid]) {
// peak index is before mid.
hi = mid;
}else { // peak index is mid.
return mid;
}
}
return -1; // no peak.
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
LeetCode 1385. Find the Distance Value Between Two Arrays (0) | 2022.06.10 |
---|---|
LeetCode 367. Valid Perfect Square (0) | 2022.06.09 |
LeetCode 35. Search Insert Position (0) | 2022.06.07 |
LeetCode 374. Guess Number Higher or Lower (0) | 2022.06.04 |
LeetCode 704. Binary Search (0) | 2022.06.03 |