Find Peak Element
来源:互联网 发布:程序员入门基础 编辑:程序博客网 时间:2024/04/28 12:12
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.
题目解析:
(1)要找峰值,如果当前那个点是下降的,那肯定是在前面
(2)如果当前那个点是上升的,那肯定是在后面。
跟跑山道理是相同的啊
#include <iostream>#include <vector>using namespace std;int findPeakElement(const vector<int> &num) {int size = num.size();if(size <= 1 )return 0;int begin = 0;int end = size - 1;int mid = (begin+end)/2;while(begin <= end){int midBer = mid - 1;int midAft = mid + 1;if(midBer < 0 && num[mid] > num[midAft])return mid;if(midAft >= size && num[mid] > num[midBer] )return mid;if(num[mid] > num[midBer] && num[mid] > num[midAft])return mid;if(num[mid] < num[midBer] && num[mid] > num[midAft])end = mid-1;else if(num[mid] > num[midBer] && num[mid] < num[midAft])begin = mid + 1;else if(num[mid] < num[midBer] && num[mid] < num[midAft])begin = mid + 1;mid = (begin+end)/2;}return 0;}int main(void){vector<int> num;num.push_back(6);num.push_back(5);num.push_back(4);num.push_back(3);cout << findPeakElement(num) << endl;system("pause");return 0;}
0 0
- [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]
- Leetcode Find Peak Element
- Linux命令行与shell脚本编程-part1-基本bash shell命令
- 第二周
- Android Studio 安装配置(for Windows)
- Spring之请求分发(Dispatching Requests) 之include方法
- java设计模式 -------- 行为模式 之 策略模式(3)
- Find Peak Element
- C语言程序设计实践3.8 Volume
- 网络流 -- Alice's Chance(二分图多重最大匹配/最大流)
- char 与 unsigned char的本质区别
- 学习Unity3D之高级查询。
- Qt实现系统托盘
- Buying Coke +uva+记忆化搜索
- JPA初识
- 访问基类成员