【Leetcode】【Medium】Find Peak Element
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:
直接想到的思路是,由于num[-1]是负无穷,因此num[0]对于它的previous neighbor是上升的,只需从num头开始遍历,找到第一个num[i] > num[i + 1]的数,那么i就是Peak Element;
算法虽然看上去已经很高效,但是,时间复杂度o(n);
代码:
class Solution {
public:
int findPeakElement(const vector<int> &num) {
int n = num.size();
for (int i = ; i < n; ++i) {
if (num[i - ] > num[i])
return i - ;
}
return n - ;
}
};
解题思路2:
o(n)的时间复杂度还是可以继续优化的,o(n)继续优化,那就是思考有没有o(logn)的算法,比较常见出现logn的算法模式是:分治算法,二分搜索等,都是一个思路,一次考察数列的一半;
由于题目中说,对于多个peak element,我们只需找到一个就可以了;同时,由于num[-1] = num[n] = -∞,因此数组中至少有一个peak element;那么设置begin、mid、end三个index分别指向数组的起始,中间和结尾:
1、如果num[mid] > num[mid + 1],说明在begin和mid 之间,至少存在一个peak element,因此只考察数组前半段就可以了;
2、如果num[mid] < num[mid + 1], 说明在mid + 1和end之间,至少存在一个peak element,因此只考察数组后半段就可以了;
(原数组相邻元素都不相等,不用考察相等的情况)
另,为什么选择mid和mid+1比,而不是mid和mid-1比,因为begin始终小于end(循环条件),而mid取(begin + end) / 2,mid有可能等于begin,因此mid+1一定存在,而mid-1有可能越界;
因此,代码:
class Solution {
public:
int findPeakElement(const vector<int> &num) {
int begin = ;
int end = num.size() - ;
while (begin < end) {
int mid = (begin + end) / ;
if (num[mid] > num[mid+])
end = mid;
else
begin = mid + ;
}
return begin;
}
};
但是实际运行中,思路2并不比思路1快多少,因为思路2在数据集中才能有效果,如果在小数据集,思路2的操作步骤比比思路1还要多,因此可能更慢;
【Leetcode】【Medium】Find Peak Element的更多相关文章
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【LeetCode题意分析&解答】37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...
- 【LeetCode题意分析&解答】35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the ...
- 【leetcode刷题笔记】Find Peak Element
A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ ...
- ACM金牌选手整理的【LeetCode刷题顺序】
算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...
- 【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists
[Q19] Given a linked list, remove the n-th node from the end of list and return its head. Example: G ...
- 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman
[Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...
- 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number
[Q7] 把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...
- 【LeetCode算法题库】Day1:TwoSums & Add Two Numbers & Longest Substring Without Repeating Characters
[Q1] Given an array of integers, return indices of the two numbers such that they add up to a specif ...
- 【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum
[Q13] Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Valu ...
随机推荐
- java BufferedImage 合成多张图片 - 因为JPEGImageEncoder 不能用
java BufferedImage 合成多张图片 public void createPicTwo2(int x,int y) { try { //读取第一张图片 ...
- 【OpenCV-Python】-几何变换
涉及函数: cv2.getPerspectiveTransform()cv2.warpAffine() 接收的参数是2✖️3的变换矩阵cv2.warpPerspective() 接收的参数是3✖️3的 ...
- 更好的理解MVC
mvc除了将数据层和逻辑层分离外,还有更好的优化了代码结构 m只和c交互,v也只和c交互,m与v的交互需要通过c,一共只用考虑4条路 如果不是这样的话,m v c需要考虑和每个人交互,那么就是要考虑 ...
- 1.5 js基础
1.变量.参数.return可以装任何东西. 2.什么时候使用window.onload? 当操作元素时 3.日期对象:在创建日期对象的时候它的日期是不会改变的. ...
- MdiContainer
/// <summary> /// 显示form /// </summary> /// <param name="form">要显示的form& ...
- 在centos linux上安装docker
前置条件 64-bit 系统 kernel 3.10+ 1.检查内核版本,返回的值大于3.10即可. $ uname -r 2.确保yum是最新的 $ yum update 3.安装 Docker y ...
- html空白文字宽度
原文链接 名称 编号 描述 不断行的空白(1个字符宽度) 半个空白(1个字符宽度) 一个空白(2个字符宽度) 窄空白(小于1个字符宽度) 小写加分号!
- Java - 深拷贝技巧
先让我描述一下问题:我在某Action(struts2.x)-A中写了一个功能P,以当前用户的某个标识F == 1时需要走这个功能,而且这个功能因某些原因已经侵入到了其他一些method中.顺便一提, ...
- Error:Execution failed for task ':app:processAnzhiDebugAndroidTestResources'. > No slave process to process jobs, aborting
环境 Android Studio 3.0 错误 Error:Execution failed for task ':app:processAnzhiDebugAndroidTestResources ...
- 前端(二):css样式
本节笔记根据css中文手册整理,内容已做成思维导图.下载地址https://files.cnblogs.com/files/kuaizifeng/css.xmind.zip. css(Csacadin ...