【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 ...
随机推荐
- Robot Framework(AutoItLibrary库操作计算器)
操作计算器的例子 我们以 Windows 自带的计算器的为例,来使用 AutoItLibrary 库.创建 AutoIt 测试用例,在运行测试用例 1.定位计算器中的一些按钮的ClassnameNN ...
- 参数化登录QQ空间实例
通过参数化的方式,登录QQ空间 实例源码: # coding:utf-8 from selenium import webdriver import unittest import time clas ...
- JavaScript 函数用途
在JavaScript中,函数可以:被赋值给一个变量,被赋值为对象的属性.作为参数被传入别的函数.作为函数的结果被返回.用字面量来创建. 1. 赋值给一个变量 //声明一个函数,接受两个参数 func ...
- CSS的引入
CSS的引入方式: 1.将样式规则写在css样式文件中,再以<link>标签引入. <link rel=stylesheet type="text/css" hr ...
- 用一个词(TASPK)牢记C程序内存布局
一个典型的C程序内存布局,从低地址到高地址分别为: 1. text (正文段,即代码段 Code Segment) 2. data (已经初始化的数据段) 3. bss (未被初始化的数据段 Bloc ...
- ormLite注解小记
注解是特殊的代码标志已在Java版本开始,要指定什么类和字段存储在数据库中,ORMLite支持其自己的注解(@ DatabaseTable @ DatabaseField)或更多的标准注解从javax ...
- 判断网站域名是否被GFW(墙)过滤屏蔽了
GFW:Greate Firewall Of China中国防火长城: 描述: 1.今天所属的一个域名被告诉不能访问了,赶紧自己测试了一下,发现可以,然后对方试了下说是不行,然后仔细按对方说的一步步操 ...
- centos6.x硬件信息统计脚本
#!/bin/bash Line='===========' #linux发行版名称 if [[ -f /usr/bin/lsb_release ]]; then OS=$(/usr/bin/lsb_ ...
- C#语言-03.逻辑控制语句
a. 逻辑控制语句: i. 条件语句:先对条件判断,然后根据判断结果执行不同的分支 . If 和 if-else:判断“布尔表达式的值”来决定执行那个代码块 a. 语法:if(布尔表达式){ b. 布 ...
- C# Windows服务创建应用
创建项目 1.创建windows服务项目 2.右键点击Service1.cs,查看代码, 用于编写操作逻辑代码 3.OnStart函数在启动服务时执行,OnStop函数在停止服务时执行.代码中OnSt ...