【LeetCode & 剑指offer刷题】查找与排序题9:Find Peak Element

本文探讨了在数组中寻找峰值元素的两种方法,一种是通过遍历找到最大值,另一种是采用二分查找思想提高效率。峰值元素是指大于其邻居的元素,文章提供了C++代码实现,并解释了算法复杂度。

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

Find Peak Element

A peak element is an element that is greater than its neighbors.
Given an input array   nums , where   nums[i] ≠ nums[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   nums[-1] = nums[n] = -∞ .
Example 1:
Input: nums = [1,2,3,1] Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [ 1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.

C++
 
//问题:找极大值元素(返回任意一个极大值均可)
/*
方法一:找最大值一定是极大值
O(n)
*/
class Solution
{
public :
    int findPeakElement ( vector < int >& nums )
    {
        int n = nums . size ();
        if ( n == 0 ) return - 1 ; //为空时,返回-1
        int max_index = 0 ;
        for ( int i = 0 ; i < n ; i ++) //找序列中的最大值,一定是极大值
        {
            if ( nums [ i ]> nums [ max_index ]) max_index = i ;
        }
        return max_index ;
    }
};
 
/* 掌握
方法二:借助二分查找思路
right指的数比后一个数大,left指的数比前一个数大,当两个“指针”相遇时,就可以满足极大值条件(两个指针按二分跨度走,故效率较高)
有点像lower_bound函数
O(logn)
*/
class Solution
{
public :
    int findPeakElement ( vector < int >& nums )
    {
        if ( nums . empty () return - 1 ; // 为空时,返回 -1
       
         int left = 0 , right = nums . size ()- 1 ;
        while ( left < right ) //left = right 时退出循环,结果是 left,right,mid 均指向极大值位置
        {
            int mid = ( left + right )/ 2 ;
            if ( nums [ mid ] < nums [ mid + 1 ]) //如果中间值比右边值小,说明峰值在右边
                left = mid + 1 ;
            else // 如果中间值比右边值大,说明峰值在左边(包括 a[mid] ,故取 right=mid
                right = mid ;
        }
      
        return right;
      
    }
};
 
 
 

 

转载于:https://www.cnblogs.com/wikiwen/p/10225949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值