-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 0852_Peak_Index_in_a_Mountain_Array.java
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// id: 852 | ||
// Name: Peak Index in a Mountain Array | ||
// link: https://leetcode.com/problems/peak-index-in-a-mountain-array/ | ||
// Difficulty: Medium | ||
|
||
class Solution { | ||
public int peakIndexInMountainArray(int[] arr) { | ||
int peakIndex = 0; | ||
int left = 0; | ||
int right = arr.length - 1; | ||
|
||
while (left < right) { | ||
int mid = ( left + right ) / 2; | ||
|
||
// check if at left peak | ||
if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]) { | ||
peakIndex = mid; | ||
break; | ||
} else if (arr[mid] > arr[mid-1]) { | ||
// peak is at right | ||
left = mid ; | ||
} else if (arr[mid] > arr[mid+1]) { | ||
right = mid ; | ||
} | ||
} | ||
|
||
|
||
return peakIndex; | ||
} | ||
} |