Leetcode 162 - Find Peak Element(二分)
来源:互联网 发布:js增加表格指定行 编辑:程序博客网 时间:2024/06/05 15:22
题意
给定一个数组,找任意一个极大值。
思路
算法1
暴力用vector
维护一个单调减的序列。最后返回第一个元素就好。
算法2
首先,只有一个元素的时候我们特判一下。
然后我们在求极值点的时候,假设当前位置在m,那么我们需要和m - 1以及m + 1的位置上的数进行比较。于是自然就需要考虑一下0和n - 1的边界情况。对于n - 1的边界情况,我们可以在vector
的最后push一个INT_MIN
。然后对于0的情况,我们可以将二分的左边界设置为1。如果在1到n - 1都没有找到极值点的话,那么结果一定为0.
于是,我们将二分的起点设置为l = 1, r = n - 1
:
am>am+1 且am>am−1 :m就为极值点。am<am+1 :说明[m + 1, r]存在极值点,于是l = m + 1
。am<am−1 :说明[l, m - 1]存在极值点,于是r = m - 1
。
代码
class Solution {public: int findPeakElement(vector<int>& a) { int n = a.size(); if (n == 1) return 0; a.push_back(INT_MIN); int l = 1, r = n - 1, m; while (l <= r) { m = l + (r - l >> 1); if (a[m] > a[m - 1] && a[m] > a[m + 1]) return m; if (a[m] < a[m + 1]) l = m + 1; else r = m - 1; } return 0; }};
0 0
- Leetcode 162 - Find Peak Element(二分)
- [leetcode] 162 Find Peak Element(二分)
- [leetcode-162]Find Peak Element(c)
- LeetCode(162) Find Peak Element
- leetcode-二分查找:Find Peak Element
- LeetCode Find Peak Element(二分查找法)
- LeetCode(162) Find Peak Element
- [leetcode 162] Find Peak Element
- leetcode-162 Find Peak Element
- [LeetCode 162]Find Peak Element
- LeetCode 162 Find Peak Element
- [leetcode] #162 Find Peak Element
- Find Peak Element - LeetCode 162
- Leetcode[162]-Find Peak Element
- leetcode-162-Find Peak Element
- !leetcode[162]:Find Peak Element
- LeetCode(162) Find Peak Element
- [Leetcode 162] Find Peak Element
- Mac OS X下完全卸载MySQL
- 非常好的介绍流形假设文章
- 《MySQL必知必会》学习笔记九(组合查询&全文本搜索)------掌握部分
- Web开发利器-Fiddler简介
- Verilog中wire和reg数据类型的区别
- Leetcode 162 - Find Peak Element(二分)
- DELPHI和BCB的版本定义宏全集 VER130 VER140 VER145 VER150
- c语言 哈夫曼编码
- 蓝桥杯基础练习 回形取数
- 这儿有自学前端开发的吗-
- IPV6 Socket编程
- 深入研究java.lang.ThreadLocal类
- wrk 压力测试
- HOJ cake