一、搜索插入位置
. - 力扣(LeetCode)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left =0;
int right = nums.size()-1;
int mid = (left+right)/2;
while(left<=right)
{
if(nums[mid]<target)
{
left = mid+1;
}
else if(nums[mid]>target)
{
right = mid-1;
}
else{
return mid;
}
mid = (left+right)/2;
}
return left;
}
};
二、825.山脉数组的峰顶索引
852. 山脉数组的峰顶索引
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int left = 0;
int right = arr.size()-1;
int mid = (left+right)/2;
while(left<right)
{
if(arr[mid-1]>arr[mid])
{
right = mid;
mid = (left+right)/2;
}
else if(arr[mid]<arr[mid+1])
{
left = mid;
mid = (left+right)/2;
}
else{
return mid;
}
}
return left;
}
};