在部分递增和部分递减的数组中查找某个元素

23 篇文章 0 订阅


给定一个整数数组,它的前一部分严格的递增,后一部分严格递减。从数组中搜索某个元素。

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);
}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值