Find Peak Element --leetcode
来源:互联网 发布:男内裤 知乎 编辑:程序博客网 时间:2024/05/18 02:47
原题链接:https://oj.leetcode.com/problems/find-peak-element/
题目大意:给定一个相邻元素不相等的数组,找出其中的一个局部最大值,返回对应下标。
方法1:顺序遍历。
本题的一个重要特点是,从第一个元素开始,若其大于相邻的后续元素,则第一个元素就是一个局部最大值,返回即可。若其小于相邻的后续元素,则第二个元素大于第一个元素。如此,一一遍历数组,第一次出现,第i个元素若大于其相邻后续元素,则该元素就是一个局部最大值,返回即可。代码如下:
- class Solution {
- public:
- int findPeakElement(const vector<int> &num) {
- for(int i=1;i<num.size();i++){
- if(num[i]<num[i-1])
- return i-1;
- }
- return num.size()-1;
- }
- };
时间复杂度:最坏O(N)
方法2:二分查找
思路:如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。
- class Solution {
- public:
- int findPeakElement(const vector<int> &num) {
- int left=0,right=num.size()-1;
- while(left<=right){
- if(left==right)
- return left;
- int mid=(left+right)/2;
- if(num[mid]<num[mid+1])
- left=mid+1;
- else
- right=mid;
- }
- }
- };
题目不错,是binary search的延续,可以和二分查找相关的算法一起做个总结。
0 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
- Codeforces Round #287 (Div. 2) C
- Flex技术中的陷阱
- cocos2d-x 3.2 之 三消类游戏——万圣大作战 (第二篇)
- leetcode Question 83: Restore IP Addresses
- ECSHOP添加广告位的方法,并且去掉广告链接
- Find Peak Element --leetcode
- Codeforces 507C - Guess Your Way Out! (思维)
- Install Linux Kernel - 通用标准
- Minimum Depth of Binary Tree leetcode
- Intent ( 意图 )
- Android 控件:ImageView、ProgressBar、AlertDialog、ProgressDialog
- [LeetCode] Word Break, Solution
- 使用node.js和socket.io实现多人聊天室
- WordPress4.1英文版转中文版