Find Peak Element—LeetCode
来源:互联网 发布:淘宝标题品牌侵权 编辑:程序博客网 时间:2024/04/28 21:58
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.
1、顺序查找
int findPeakElement(const vector<int> &num) { if(num.size()==1||num.at(0)>num.at(1)) return 0; if(num.at(num.size()-1)>num.at(num.size()-2)) return num.size()-1; int i=1; for(;i<num.size()-1;i++) { if(num.at(i)>num.at(i-1)&&num.at(i)>num.at(i+1)) break; } return i; }
2、递归查找-传值作为判断条件
int findPeakElement(const vector<int> &num) { if(num.size()==1||num.at(0)>num.at(1)) return 0; if(num.at(num.size()-1)>num.at(num.size()-2)) return num.size()-1; bool isFind=false; int index=-1; findPeak(num,1,num.size()-2,isFind,index); return index; } void findPeak(const vector<int> &num,int low,int high,bool &isFind,int &index) { if(low>high||isFind) return; int mid=(low+high)/2; if(isPeak(mid,num)) { isFind=true; index=mid; return; } findPeak(num,low,mid-1,isFind,index); findPeak(num,mid+1,high,isFind,index); } bool isPeak(int &index,const vector<int> &num) { if(num.at(index)>num.at(index-1)&&num.at(index)>num.at(index+1)) return true; return false; }
3、二分查找-分析该题的特征,在mid处判断num.at(mid)与num.at(mid+1)大小,假使num.at(mid+1)较大:
a、mid+2~high单调递增,则high为peak;
b、非单调递增,必定出现一个较左边邻居小的数,此时也可查找peak;
int findPeakElement(const vector<int> &num) { if(num.size()==1) return 0; int low=0; int high=num.size()-1; int mid=0; while(low<high) { mid=(low+high)/2; if(num.at(mid)>num.at(mid+1)) { high=mid; } else { low=mid+1; } } return low; }
0 0
- 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
- 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
- 【读书笔记】机器学习实战-kNN(2)
- E-R模型、E-R分析介绍
- Android Studio系列教程一--下载与安装
- 字典树
- 详解一致性哈希(consistent hashing)算法
- Find Peak Element—LeetCode
- 06 Trident DRPC
- Ruby Block
- linux设备驱动第五篇:驱动中的并发与竟态
- Java基础—IO流(一)
- 飞思卡尔智能车
- Oracle11g安装后如何使用PL/SQL
- 复制别人的用户权限设计
- 【转】2014年中国系统架构师大会——腾讯云安全实践