leetcode_Find Peak Element
来源:互联网 发布:网络音频编码器 编辑:程序博客网 时间:2024/04/30 07: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.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:
开始感觉很难下手,数组不是有序的,时间要求是log(n),最后想到一种方法,mid=(left+right)/2;if(num[mid]<num[mid+1])left=mid+1;else right=mid,这种方式还真的可以找到其中的一个peak,所以根据时间复杂度的提示反而提醒了思路。
代码:
public int findPeakElement(int[] num) { int left=0,right=num.length-1; int mid=0; int num1=0,num2=0; while(left<=right){ if(left==right) return left; mid=(left+right)/2; if(num[mid]<num[mid+1]) left=mid+1; else right=mid; } return 0; }
0 0
- leetcode_Find Peak Element
- [LeetCode] Find Peak Element
- Find Peak Element
- Leetcode:Find Peak Element
- Find Peak Element
- Find Peak Element
- Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- Find Peak Element
- Find Peak Element
- Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Find Peak Element [Medium]
- 优质代码
- samba install
- frame 和 bounds 区别
- UML设计中的箭头详解
- public 修饰符
- leetcode_Find Peak Element
- 汇编中各寄存器的作用
- mcupdate详解
- 百度贴吧XSS漏洞可控制已登录的贴吧账号(删帖、修改资料等)
- 为Eclipse或MyEclipse安装PHP插件
- 代码编辑器使用范例
- 【多线程_提高篇】 thread.stop禁用的原因
- MySQL 获得当前日期时间(以及时间的转换)
- Python学习-格式化数据并排序