题目地址:
https://oj.leetcode.com/problems/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.
Your solution should be in logarithmic complexity.
方法:
有两点需要注意的:
0、复杂度要为O(log n)
1、注意审题
我第一次做,以为要返回所有peak element,想破头都找不到一个log复杂度的办法,后来读题才发现是让你找一个就行。
那就单纯了
因为只要你找一个,所以首先看中间元素是不是,如果是直接返回中间那个,如果不是就跟着比中间大的元素那边走,砍掉另一半。如果两个都比中间元素大就随意走一边。
证明也比较简单。
往大的那边走的区域肯定存在一个peak element,分两种情况
0、全是大于号:那么就是该区域最后一个值。
1、有小于号:至少有一个大于号和小于号配对,即存在peak element
因此,大的区域那边总会有peak element。
不明白的同学留言
全部代码:
class Solution { public: int findPeakElement(const vector<int> &num) { if (num.size() == 1) return 0; return trueStuff(num,0,num.size() - 1); } int trueStuff(const vector<int> &num,int start,int fin) { int mid = (start + fin) / 2; if (mid - 1 < 0) return num[mid] > num[mid+1] ? mid : mid + 1; if (mid + 1 >= num.size()) return num[mid] > num[mid-1] ? mid : mid - 1; if (num[mid-1] < num[mid] && num[mid+1] < num[mid]) return mid; return num[mid] > num[mid-1] ? trueStuff(num,mid + 1,fin) : trueStuff(num,start,mid - 1); } };