局部极大值

来源:互联网 发布:日本人对二战 知乎 编辑:程序博客网 时间:2024/06/05 00:24

leetcode练习地址

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.


class Solution {public:    int findPeakElement(vector<int>& nums) {        int iLeft = 0;        int iRight = nums.size()-1;        int iMid = (iLeft + iRight) / 2;        while(iLeft != iRight){            if(nums[iMid] > nums[iMid+1])                iRight = iMid;            else                iLeft = iMid+1;            iMid = (iLeft + iRight) / 2;        }        return iMid;    }};

局部极大值在[i,n]   

原创粉丝点击