题目描述:

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
 
结尾无空行
 
 
 

分析:

•此题关键词:单峰数组、峰值(最大值)、递增、递减  时间复杂度O(log n)

•题目要求找出单峰数组的最大值所在位置,并返回它的值

思路:

题目很简单,要求时间复杂度为O(log n),所以采用二分搜索的方法,一边判断mid下标所在的元素值是否比左边和右边都大,一边递归调用方法缩小查找范围,直到找到元素。

 


代码:

#include <bits/stdc++.h>
using namespace std;


int binary_sort(int start, int end, int a[]){
    int mid = (start + end)/2;
    if(start > end) return -1;
    if(a[mid] >= a[mid - 1] && a[mid] >= a[mid + 1]) return mid;
    else if(a[mid] > a[mid - 1] && a[mid] < a[mid + 1])return binary_sort(mid + 1, end, a);
    else if(a[mid] < a[mid - 1] && a[mid] > a[mid + 1])return binary_sort(start, mid, a);
} 

int main()
{
    int n, a[10000];
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
  int flag = binary_sort(0, n - 1, a);
     cout << a[flag] << endl;
    return 0;
}

总结:

二分实质上是分治思想的体现,当然只有在相对有序的数组里才能用二分(一般是递增或是递减数组,本题为先递增后递减),在查找的同时逐步缩小查找范围(每次都减半)。
posted on 2021-09-28 19:02  Aheador  阅读(88)  评论(0编辑  收藏  举报