A 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] = -∞.
Example
in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Note:
Your solution should be in logarithmic complexity.
Solution
- Java: iteration+recursive
(Find-Peak-Element.java) download
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
| public class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
return bs(nums,0,n-1);
}
public int bs(int[] nums, int start, int end){
if(start==end)
return start;
int mid1 = start+(end-start)/2;
int mid2 = mid1+1;
if(nums[mid1]>nums[mid2])
return bs(nums, start,mid1);
else
return bs(nums, mid2,end);
}
}
public class Solution {
public int findPeakElement(int[] nums){
int end = nums.length-1;
int start = 0;
while(start<end){
int mid1 = start+(end-start)/2;
int mid2 = mid1+1;
if(nums[mid1]>nums[mid2])
end = mid1;
else
start = mid2;
}
return start;
}
}
|
(Find-Peak-Element.py) download
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
| class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
start = 0
end = len(nums)-1
while start <= end:
mid = (start+end)/2
if mid-1 < 0 and mid+1 < len(nums):
if nums[mid] > nums[mid+1]:
return mid
else:
start = mid+1
if mid+1 >= len(nums) and mid-1>=0:
if nums[mid] > nums[mid-1]:
return mid
else:
end = mid-1
if mid-1 >=0 and mid+1<len(nums):
if nums[mid] > nums[mid-1] and nums[mid] > nums[mid+1]:
return mid
elif nums[mid] < nums[mid-1]:
end = mid-1
else:
#nums[mid] < nums[mid+1]:
start = mid+1
return start
if __name__ == "__main__":
sol = Solution()
sol.findPeakElement([3,2,1])
|