标题2(1) maximum number in a unimodal array (25 分)
You are a given a unimodal array of n distinct elements, meaning that its entries are in increasing order up until its maximum element, after which its elements are in decreasing order. Give an algorithm to compute the maximum element that runs in O(log n) time.
输入格式:
An integer n in the first line, 1<= n <= 10000. N integers in the seconde line seperated by a space, which is a unimodal array.
输出格式:
A integer which is the maximum integer in the array
输入样例:
7
1 2 3 9 8 6 5
结尾无空行
输出样例:
9
结尾无空行
注释:题目大概意思是,给出一组基本有序数找峰值。可以利用二分搜索分为三种情况
(1)中间的数i就是最大值,i-1<i, i>i+1;
(2) 中间的数在峰值的左边,小于峰值,i<i+1,下标右移;
(3)中间的数在峰值的右边,大于峰值,i>i+1,下标左移
特殊情况:峰值在第一个,或者是在最后一个
#include <iostream>
using namespace std;
int BinarySeach(int a[], int m, int n);
int main()
{
int a[100001];
int n, m=1;
cin>>n;
for(int i=1;i<=n;i++) //注意这里的起始下标是1
cin>>a[i];
int res=BinarySeach(a,1,n);
cout<<res<<endl;
return 0;
}
int BinarySeach(int a[], int m, int n)
{
int mid=n/2;
while(a[mid]<a[mid-1]&&mid>=1)
mid--;
while(a[mid]>a[mid-1]&&mid<=n)
mid++;
return a[mid-1];
}