-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_FindThePeakElement.py
More file actions
25 lines (22 loc) · 886 Bytes
/
02_FindThePeakElement.py
File metadata and controls
25 lines (22 loc) · 886 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
# Question link https://leetcode.com/problems/find-peak-element/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
n = len(nums)
if (n==1): #For only one elements
return 0
if (nums[0] > nums[1]) : #For peak at Oth index
return 0
if (nums[n-1] > nums[n-2]): #For peak in n-1th index
return n-1
low , high = 1 , n - 2
while(low <= high):
mid = (low + high) // 2
if ((nums[mid] > nums[mid - 1]) and (nums[mid] > nums[mid+1])):
return mid # the peak is in the mid
# If peak is in right half
elif (nums[mid] > nums[mid - 1]):
low = mid + 1
else:
# peak is in left half
high = mid - 1
return -1