[LeetCode]Find Peak Element
来源:互联网 发布:商品条码数据库 编辑:程序博客网 时间:2024/06/06 08:30
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.
代码:
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.
思路1: 遍历,O(N)
代码1:
public int findPeakElement1(int[] num) {//暴力 for(int i = 0; i < num.length; ++i){ if(i+1 < num.length){ if(num[i] > num[i+1] && ((i -1 >= 0 && num[i] > num[i-1])||(i-1 < 0))){ return i; } }else { if(i-1 < 0 || i -1 >=0 && num[i] > num[i-1]){ return i; } } } return 0; }思路2:二分,
代码:
public int findPeakElement(int[] num) {// int l = 0, r = num.length - 1, mid; while (l < r){ mid = l + (r - l) / 2; if(num[mid] < num[mid + 1]) l = mid + 1; else r = mid; } return num[l]; }
1 0
- [LeetCode] Find Peak Element
- Leetcode:Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode Find Peak Element
- Leetcode: Find Peak Element
- 【leetcode】Find Peak Element
- leetcode:Find Peak Element
- 【Leetcode】Find Peak Element
- LeetCode:Find Peak Element
- LeetCode:Find Peak Element
- [LeetCode] Find Peak Element
- LeetCode Find Peak Element
- Linux设备驱动开发环境的搭建
- Blackhat上没有讲的SAP手机安全如何黑掉世界500强CEO手机
- java基础知识2
- 第一次ACM,值得纪念的回忆
- 计算程序耗时的简单实现代码
- [LeetCode]Find Peak Element
- 【转】算法还重要吗?
- film faced plywood - LongDa Wood
- 【翻译自mos文章】ORA-19815, Flashback Logs-Space management
- 李红霞作业第二章第20题
- hdu 3371 Connect the Cities
- 【更新】排序算法比较:插入排序,冒泡排序,归并排序,堆排序,快速排序,计数排序,基数排序,桶排序
- c++内存管理
- 简单的adajent_find_t copy_t count_1_t简单的实现