162. Find Peak Element

来源:互联网 发布:js页面获取当前时间 编辑:程序博客网 时间:2024/05/16 19:39

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.
任意回一个峰值就ok了
二分查找法:

int findPeakElement(const vector<int> &num) {        int low = 0, high = num.size() - 1;        while (low < high - 1) {            int mid = (low + high) / 2;            if (num[mid] > num[mid - 1] && num[mid] > num[mid + 1])                 return mid;            else if (num[mid] > num[mid + 1])                     high = mid - 1;                 else                     low = mid + 1;            }        return num[low] > num[high] ? low : high;    }
0 0
原创粉丝点击