题目来源:https://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.
click to show spoilers.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
最容易想到的方法就是自左至右遍历数组,如果某元素比他左右元素都大,则返回该顶点。
class Solution162{ public: int findPeakElement(vector<int>& nums){ //顺序查找 int n = nums.size(); if (n == 1) return 0; else if (nums[0] > nums[1]) return 0; else if (nums[n - 1] > nums[n - 2]) return n - 1; for (int i = 1; i < n - 1; ++i){ if (nums[i - 1] <= nums[i] && nums[i + 1] <= nums[i]) return i; } return -1; } };
否则与最右边的元素一致,将右边界挪到mid的位置。
这个方法的原理就是当左边界方向为“增长”,右边界方向为“下降”时,二者围出的区域必有一个顶点。
class Solution162{ public: int findPeakElement(vector<int>& nums){ //二分查找 int n = nums.size(); if (n == 1) return 0; int left = 0; int right = n - 1; int mid = 0; while (left < right){//注意该处是< mid = (left + right) / 2; if (nums[mid] <= nums[mid + 1]) left = mid + 1; else{ right = mid; } } return left; } }; int main() { Solution164 soulution; vector<int> v = { 1, 2, 3, 1 }; cout << soulution.findPeakElement(v); system("pause"); return 0; }