题目:
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.
峰值元素大于其两边的邻居元素,给定一个num[i] ≠ num[i+1]的输入数组,找到峰值元素并返回其下标索引。
给定的数组可能包含多个峰值元素,如果是这种情况,返回任何一个峰值元素下标即可。
假定num[-1] = num[n] = -∞
.
note:
算法的时间复杂度要是对数复杂度
思路一:
顺序搜索,找到每个局部峰值元素,之后与全局峰值元素相对比,大于全局峰值元素则更新全局峰值元素。
代码:8ms
class Solution { public: int findPeakElement(vector<int>& nums) { int peakIndex = 0; int n = nums.size(); for(int i=1; i<n-1; i++){ if(nums[i]>nums[i-1] && nums[i]>nums[i+1]){ if(nums[i]>nums[peakIndex]){ peakIndex = i; } } } if(nums[n-1]>nums[peakIndex]){ peakIndex = n-1; } return peakIndex; } };
代码:8ms
class Solution { public: int findPeakElement(vector<int>& nums) { for(int i = 1; i < nums.size(); i ++) { if(nums[i] < nums[i-1]) { return i-1; } } return nums.size()-1; } };思路二:
基于迭代+二分查找的方法,通过二分查找的方法找到局部最优,因为存在峰值元素,则该序列存在一定的顺序。
代码:8ms
class Solution { public: int findPeakElement(vector<int>& nums) { return backtracking(nums, 0, nums.size()-1); } int backtracking(vector<int>& nums, int low, int high){ if(low == high){ return low; }else{ int mid1 = (low+high)/2; int mid2 = mid1 + 1; if(nums[mid1]>nums[mid2]){ return backtracking(nums, low, mid1); }else{ return backtracking(nums, mid2, high); } } } };思路三:
采用二分查找的方法;
代码:8ms
class Solution { public: int findPeakElement(vector<int>& nums) { int low = 0; int high = nums.size()-1; while(low < high){ int mid1 = (low + high)/2; int mid2 = mid1 + 1; if(nums[mid1]<nums[mid2]){ low = mid2; }else{ high = mid1; } } return low; } };
转载地址:https://leetcode.com/discuss/17793/find-the-maximum-by-binary-search-recursion-and-iteration