2(1) maximum number in a unimodal array

标题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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值