思路:最多三次二分法:第一次先用二分法找出峰值,后两次依次对峰值左、右侧二分查找target
这种交互式问题 建议写个参数是数组的对应函数 测试下;
class MountainArray
{
public:
int get(int index);
int length();
};
int findInMountainArray(int target, MountainArray &mountainArr)
{
//二分法找峰值
int l = 0, len = mountainArr.length(), r = len - 1;
int mid = 0;
int res = -1;
while (l < r)
{
mid = (l + r) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) //如果小于右边元素得值 肯定峰值在右侧
{
l = mid + 1;
}
else
{
r = mid;//针对案例[1,5,2] 2 做出调整
}
}
int mountainTop = l; //得到峰值对应的索引
//划分左右两端 分别二分法
l = 0;
r = mountainTop;
while (l <= r)
{
mid = (l + r) / 2;
int now=mountainArr.get(mid);
if (now == target)
{
res = mid;
break;
}
else if (now < target)
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
if (res != -1)//如果在左端找到target r直接eturn
return res;
//左侧没找到就去右侧二分
l = mountainTop;
r = len - 1;
while (l <= r)
{
mid = (l + r) / 2;
int now=mountainArr.get(mid);
if (now == target)
{
res = mid;
break;
}
else if (now > target)
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
return res;
}