cpp
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right = n - 1, ans = n;
while (left <= right) {
int mid = ((right - left) >> 1) + left;//如果不加left那么就只要right与left
if (target <= nums[mid]) {
ans = mid;
right = mid - 1;
}
else {
left = mid + 1;
}
}
return ans;
}
};
int main() {
Solution solution;
vector<int> nums = { 1, 3, 5, 6 ,9};
int target = 7;
int result = solution.searchInsert(nums, target);
cout << "输出: " << result << endl;
return 0;
}
分析:利用二分法,不停的逼近这个值,如果目标值小于二分法求取的中间索引的这个值,那么首先保存这个索引值,第二右边的索引值等于mid-1,就是向左去夹近。如果target大于这个值则左边界+1,每次mid的值是right-left的和>>1并且加上lef