Find Peak Element解题报告

来源:互联网 发布:虚拟机怎么安装mac os 编辑:程序博客网 时间:2024/04/28 01:46

题目描述

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.

题目思路

比较简单的一种方法是遍历数组,找到peak element,另外一种方法是二分查找。因为只要求找到一个,所以我们先从中间元素开始查找,如果中间元素比两边的都大,则返回中间元素的下标。否则,如果nums[mid-1]比nums[mid]大,则将搜索区间所有(0,mid-1)否则锁定(mid+1,n)

代码

class Solution {public:    int findPeakElement(vector<int>& nums) {        if(nums.size()<=1)            return 0;        int start=0;        int end=nums.size()-1;        int mid=0;        int n=nums.size();        while(start<=end){            mid=start+(end-start)/2;            if((mid == 0 || nums[mid] >= nums[mid - 1]) &&(mid == n-1|| nums[mid] >= nums[mid + 1]))                return mid;            else if(mid>0&&nums[mid-1]>nums[mid]){                end=mid-1;            }            else{                start=mid+1;            }        }        return mid;    }};


0 0
原创粉丝点击