Middle-题目40:162. 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.
题目大意:
寻找一个数组的峰值元素(类似于函数中的极大值)
假设num[-1]=num[n]=- ∞。
若数组中有多个峰值元素,返回任意一个都可以。
题目分析:
本题依然是一个二分查找的变形。先考虑边界情况,若数组只有1个元素,则他就是峰值;若数组只有两个元素则较大的就是峰值元素。
接下来进行二分查找,设中点为mid,考虑以下情况:
(1) mid是端点,那么只看它是否大于第二个点(倒数第二个点)即可;
(2) mid点的值大于左边又大于右边,则它就是峰值,返回即可;
(3) mid点的“邻域”是递增的,则右半边一定有峰值;
(4) mid点的“邻域”是递减的,则左半边一定有峰值;
源码:(language:c)

int findPeakElement(int* nums, int numsSize) {
    if(numsSize == 1) 
        return 0;
    else if(numsSize == 2)
        return nums[0]<nums[1];
    else {
        int mid=(numsSize-1)/2;
        if(mid == 0 && nums[0]>nums[1])
            return 0;
        else if(mid == numsSize-1 && nums[numsSize-1] > nums[numsSize-2])
            return numsSize-1;
        else if(nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1])
            return mid;
        else if(nums[mid] >= nums[mid-1] && nums[mid] <= nums[mid+1])
            return findPeakElement(&nums[mid+1],numsSize-mid-1)+mid+1;
        else 
            return findPeakElement(nums,numsSize-mid-1);
    }
}

成绩:
0ms,beats 9.38%,众数0ms,90.62%
cmershen的碎碎念:
二分查找不一定只适用于有序的数组。像本题的数组是不知道顺序的,但适用二分查找。

你可能感兴趣的:(Middle-题目40:162. Find Peak Element)