-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path162 Find Peak Element.py
76 lines (61 loc) · 1.75 KB
/
162 Find Peak Element.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# -*- coding: utf-8 -*-
"""
peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Author: Rajeev Ranjan
"""
import sys
class Solution:
def __init__(self):
self.A = None
def findPeakElement(self, nums):
"""
:type nums: list[int]
:rtype: int
"""
self.A = nums
n = len(self.A)
if n < 2:
return 0
l = 0
h = n
while l < h:
m = (l+h)/2
if self._get(m-1) < self._get(m) > self._get(m+1):
return m
elif self._get(m+1) > self._get(m):
l = m+1
else:
h = m
return -1
def _get(self, i):
if i < 0 or i >= len(self.A):
return -sys.maxint-1
else:
return self.A[i]
def findPeakElement_complicated(self, nums):
"""
:type nums: list[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return 0
l = 0
h = n
while l < h:
m = (l+h)/2
if m == 0 and nums[m] > nums[m+1]:
return m
elif m == n-1 and nums[m] > nums[m-1]:
return m
elif nums[m-1] < nums[m] > nums[m+1]:
return m
elif m+1 < n and nums[m+1] > nums[m]:
l = m+1
else:
h = m
return -1