LeetCode #162: Find Peak Element
来源:互联网 发布:form表单怎么提交数据 编辑:程序博客网 时间:2024/04/28 22:47
Problem Statement
(Source) A peak element is an element that is greater than its neighbours.
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.
Note:
Your solution should be in logarithmic complexity.
Analysis
Naive
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) for i in range(1, n - 1): num = nums[i] if num > nums[i-1] and num > nums[i+1]: return i return [0, n - 1][nums[0] < nums[n - 1]]
The optimised Binary Search
.
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ return self.search(nums, 0, len(nums) - 1) def search(self, nums, start, end): if start == end: return start elif start + 1 == end: return [start, end][nums[start] < nums[end]] else: mid = (start + end) >> 1 if nums[mid] < nums[mid - 1]: return self.search(nums, start, mid - 1) elif nums[mid] < nums[mid + 1]: return self.search(nums, mid + 1, end) else: return mid
0 0
- LeetCode(162) Find Peak Element
- [leetcode 162] Find Peak Element
- leetcode-162 Find Peak Element
- [LeetCode 162]Find Peak Element
- LeetCode 162 Find Peak Element
- [leetcode] #162 Find Peak Element
- Find Peak Element - LeetCode 162
- Leetcode[162]-Find Peak Element
- leetcode-162-Find Peak Element
- !leetcode[162]:Find Peak Element
- LeetCode(162) Find Peak Element
- [Leetcode 162] Find Peak Element
- leetcode 162: Find Peak Element
- Leetcode #162 Find Peak Element
- 【leetcode】【162】Find Peak Element
- LeetCode 162 Find Peak Element
- Leetcode 162: Find Peak Element
- LeetCode-162:Find Peak Element
- MySQL导入.sql文件及常用命令
- 获取插入表的自增ID问题
- UVa 1626
- Valid Anagram
- freemaker生成word
- LeetCode #162: Find Peak Element
- 字符串排列和组合的JAVA实现
- C#之WinForm基础 textbox控件变高,由单行输入改为多行输入
- 彼得·德鲁克:你事业的上限究竟在哪?
- Board covering problem
- MultipleTheme框架兼容RecyclerView和CardView&RecyclerView缓存机制
- MemCache 源自百度百科
- 常用HTML标签
- C1X 系列 : 多线程 (N1494)