162. Find Peak Element
我在做 binary search 的时候,没有考虑 mid 有没有被访问到的情况。
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0: return
if n == 1: return 0
if nums[0] > nums[1]: return 0
if nums[-1] > nums[-2]: return n - 1
# for i in range(1, n - 1):
# if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]: return i
'''
Since nums[-1] == nums[n] == -∞.
'''
# i = 1
# j = n - 2
# while i <= j:
# if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]: return i
# if nums[j] > nums[j - 1] and nums[j] > nums[j + 1]: return j
# mid = int((i + j) / 2)
# # in this case, I ignore to compare mid, just jump to mid + 1
# if nums[mid] > nums[mid - 1]: i = mid + 1
# else:
# j = mid
i = 1
j = n - 2
while i <= j:
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]: return i
if nums[j] > nums[j - 1] and nums[j] > nums[j + 1]: return j
mid = int((i + j) / 2)
if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]: return mid
if nums[mid] > nums[mid - 1]: i = mid + 1
else:
j = mid