算法系列—— Find Peak Element
来源:互联网 发布:java发送邮件 多邮箱 编辑:程序博客网 时间:2024/06/05 18:14
题目描述
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.
解题思路
顺序查找法
顺序遍历数组。本题的一个重要特点是,从第一个元素开始,若其大于相邻的后续元素,则第一个元素就是一个局部最大值,返回即可。若其小于相邻的后续元素,则第二个元素大于第一个元素。如此,一一遍历数组,第一次出现,第i个元素若大于其相邻后续元素,则该元素就是一个局部最大值,返回即可。
时间复杂度为O(n)
二分查找法
如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧(不包含)必包含一个局部最大值。
平均时间复杂度为O(logn)
程序实现
顺序查找
public class Solution { public int findPeakElement(int[] nums) { for(int i=1;i<nums.length;i++){ if(nums[i-1]>nums[i]) return i-1; } return nums.length-1; }}
二分查找
public class Solution { public int findPeakElement(int[] nums) { int left=0,right=nums.length-1; while(left<right){ int mid=(left+right)/2; if(nums[mid]<nums[mid+1]) left=mid+1; else right=mid; } return left; }}
阅读全文
0 0
- 算法系列—— Find Peak Element
- Find Peak Element—LeetCode
- leetcode——Find Peak Element
- LeetCode162——Find Peak Element
- leetcode 162 —— Find Peak Element
- Find Peak Element —— Leetcode
- leetcode——Find Peak Element
- 二分查找——Find Peak Element
- Algorithms—162.Find Peak Element
- leetcode刷题日记——Find Peak Element
- 【leetcode】Array——Find Peak Element(162)
- [LeetCode] Find Peak Element
- Find Peak Element
- Leetcode:Find Peak Element
- Find Peak Element
- Find Peak Element
- Find Peak Element
- LeetCode Find Peak Element
- ListView setOnItemClickListener无效原因分析
- HANA 存储过程 基础篇
- HDU1005Number Sequence
- Activity did not call finish() prior to onResume() completing原因和解决办法
- Vue(2) : Vue for Gank.io
- 算法系列—— Find Peak Element
- 调用WebService接口的方法
- Apache HttpClient 资源释放、请求超时,导致线程池用光、内存不足
- thinkphp网站支付宝异步回调验签失败问题,发现一个原因点
- Android绘图基础--Surface创建及初始化
- Xamarin for Visual Studio v4.6发布,重新设计属性页和Manifest编辑器
- 各种加密解密函数(URL加密解密、sha1加密解密、des加密解密)
- java 遍历map的方式
- Going deeper with convolutions-GoogLeNet(阅读)