给定一个整数数组,它的前一部分严格的递增,后一部分严格递减。从数组中搜索某个元素。
Given an array of integers having the property that first that array is strictly increasing then it is strictly decreasing, You have to search for a given number.
Constraint: Minimize the complexity
由于整数数组,它的前一部分严格的递增,后一部分严格递减,所以对于递增的部分 如果j==i+1那么a[i]<a[j] 对于递减部分有a[j]<a[i]。
可以使用修改的二叉搜索算法去查找数组中最大的数的位置。
即对于连续的下标i, k, j,有a[i]<a[k] and a[k] > a[j]
第一步找到此下标
第二部用二分搜索算法搜索递增部分是否有所求的值。
第三部就是搜索递减部分了。
since the array is strictly increasing first then strictly decreasing, therefore for the increasing part of the array if, i+1=j then definitely
a[i]<a[j] and for decreasing part a[j]<a[i],
we can use modified binary search to search the array.
consider the array
int[] arr = new int[] {1,3,5,7,19,221,132,56,8,6,4,2,1,-3,-17};
here we need to find k such that, for three consecutive elements i, k, j, a[i]<a[k] and a[k] > a[j]
step 1 :
so, first we need to find the ending of increasing part of the array, lets the end index of increasing part as k.
use a modified binary search to find k
step 2 :
Now search the increasing part of array using binary search
BinarySearch(int[] arr, low, k)
step 3:
and decreasing part using binarysearch
BinarySearch(int[] arr, k+1, high)
#include <iostream> using namespace std; int findK(int arr[],int low,int high) { if (high-low<2)//要考查的元素个少于3个 { return -1; } int mid = (low+high)>>1; if (arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1]) { return mid; } int n1 = findK(arr,low,mid); int n2 = findK(arr,mid,high);//将mid包含进去 是因为只考虑中间的元素 不考虑两边的元素,即不会考查mid 和 high。 如果mid是要找的元素的前一个元素,如果使用findK(arr,mid+1,high), 这种情况下找不到此元素 if (n1!=-1) return n1; if (n2!=-1) return n2; return -1; } int ICR_binarySerch(int arr[],int l,int h,int num) { } int DCR_binarySerch(int arr[],int l,int h,int num) { } int searchArr(int arr[],int length,int the_num) { int k = findK(arr,0,length-1); int res = ICR_binarySerch(arr,0,k,the_num); if (res != -1) { return res;//返回具体位置 } return DCR_binarySerch(arr,k+1,length-1,the_num); }