forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem3.java
More file actions
28 lines (27 loc) · 746 Bytes
/
Problem3.java
File metadata and controls
28 lines (27 loc) · 746 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Time Complexity - O(log n)
//Space Complexity - O(1)
//Did it run on leetcode - yes
//Your approach
/*
Use binary search on unsorted array and find middle
check for its immediate neighbors and compare
traverse to the side that is greater than middle element
*/
class Solution {
public int findPeakElement(int[] nums) {
int l = 0;
int h = nums.length - 1;
while (l<=h) {
int mid = l + (h-l)/2;
if ((mid==0 || nums[mid] > nums[mid-1]) && (mid == h ||
nums[mid]>nums[mid+1])) {
return mid;
} else if(nums[mid+1]>nums[mid]) {
l = mid+1;
} else {
h = mid-1;
}
}
return -1;
}
}