LeetCode-162 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] = -∞.

 

题目大意

给定一个数组,寻找数组当中的任意一个顶点元素(顶点元素:该点的数值大于相邻位置的数值)的位置(数组中元素不重复)。

要求:在O(log(n))时间复杂度内完成。

 

示例

E1

Input: nums = [1,2,3,1]
Output: 2

E2

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 

 

解题思路

可以通过二分搜索策略进行搜索,判断条件为mid与mid + 1位置的数值大小进行搜索。

 

复杂度分析

时间复杂度:O(log(n))

空间复杂度:O(1)

 

代码

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        return solve(nums, 0, nums.size() - 1);
    }
    //二分搜索
    int solve(vector<int>& nums, int low, int high) {
        if(low == high) 
            return low;
        
        int mid1 = (low + high) / 2;
        int mid2 = mid1 + 1;
        //寻找两个较大的数字之间的数字的位置
        if(nums[mid1] > nums[mid2])
            return solve(nums, low, mid1);
        else
            return solve(nums, mid2, high);
    }
};

 

posted @ 2019-05-29 22:07  你好哇傻小妞  阅读(165)  评论(0编辑  收藏  举报