Problem Description:
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] = -∞.
For example, in array
[1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
l = len(num)
if(l == 1):
return 0
if(l == 0):
return None
if(num[0] > num[1]):
return 0
if(num[l-1] > num[l-2]):
return (l-1)
for i in range(1,l-1):
if(num[i] > num[i+1] and (num[i] > num[i-1])):
return i
return None
Solution:
1. You have to notice the special case where the starting and ending nodes should be checked in a different way.
2. You must realize that when the length of array is less than 2, the result should be 0 or none!
Thinking:
Every time you program on leetcode, it is better to run it until you are sure that everything goes well. Because in real interview setting, it is probably impossible for you to debug your program by running it. Usually, you will be asked to write your program in a white board.
No comments:
Post a Comment