Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4729549

Browse files
author
weiy
committed
find peak element medium
1 parent 83f334c commit 4729549

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎Array/FindPeakElement.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
A peak element is an element that is greater than its neighbors.
3+
4+
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
5+
6+
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
7+
8+
You may imagine that nums[-1] = nums[n] = -∞.
9+
10+
Example 1:
11+
12+
Input: nums = [1,2,3,1]
13+
Output: 2
14+
Explanation: 3 is a peak element and your function should return the index number 2.
15+
Example 2:
16+
17+
Input: nums = [1,2,1,3,5,6,4]
18+
Output: 1 or 5
19+
Explanation: Your function can return either index number 1 where the peak element is 2,
20+
or index number 5 where the peak element is 6.
21+
Note:
22+
23+
Your solution should be in logarithmic complexity.
24+
25+
log n待续。
26+
27+
先O(n)。
28+
29+
看来测试数据不多,O(n) 的可以 beat 100%.
30+
31+
测试地址:
32+
https://leetcode.com/problems/find-peak-element/description/
33+
34+
"""
35+
class Solution(object):
36+
def findPeakElement(self, nums):
37+
"""
38+
:type nums: List[int]
39+
:rtype: int
40+
"""
41+
42+
length = len(nums)
43+
44+
for i in range(1, length-1):
45+
if nums[i-1] < nums[i] > nums[i+1]:
46+
return i
47+
48+
if length <= 2:
49+
return nums.index(max(nums))
50+
else:
51+
if nums[0] > nums[1]:
52+
return 0
53+
elif nums[-1] > nums[-2]:
54+
return length-1
55+
return None

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /