Leetcode[162] Find Peak Element
14 Nov 2015###Task1 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.
click to show spoilers.
Note: Your solution should be in logarithmic complexity.
###Python ####simple
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = len(nums) - 1
while left + 1 < right:
mid = left + (right - left) / 2
#print"left = %d, right = %d, mid = %d" % (left, right, mid)
if nums[mid] > nums[mid + 1] and nums[mid] > nums[mid - 1]:
return mid
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid
return left if nums[left] > nums[right] else right
####complex
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
imin = -1 << 31
arr = [imin for i in range(len(nums) + 2)]
for i in range(len(nums)):
arr[i + 1] = nums[i]
left = 0
right = len(arr) - 1
while left + 1 < right:
mid = left + (right - left) / 2
if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]:
return mid - 1
if arr[mid] > arr[mid - 1] or arr[mid + 1] > arr[mid]:
left = mid
else:
right = mid
if arr[left] > arr[right]:
return left - 1
else:
return right - 1
###Java
public class Solution {
public int findPeakElement(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int left = 0;
int right = nums.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (mid == 0 && nums[mid] > nums[mid + 1]) {
return mid;
} else if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) {
return mid;
}
if (nums[mid] < nums[mid + 1]) {
left = mid;
continue;
} else {
right = mid;
continue;
}
}
return nums[left] > nums[right] ? left : right;
}
}
###Points
- left + 1 < right, then mid will never reach 0 / len - 1
- nums[mid] > nums[mid + 1] and nums[mid] > nums[mid - 1] Always hold true inside loop