42 lines
915 B
C++
42 lines
915 B
C++
/*
|
|
* @Description:
|
|
* @Version: 1.0
|
|
* @Autor: zhuyijun
|
|
* @Date: 2021-12-21 14:29:47
|
|
* @LastEditTime: 2021-12-21 17:10:04
|
|
*/
|
|
/*
|
|
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
|
|
|
|
请必须使用时间复杂度为 O(log n) 的算法。
|
|
|
|
|
|
|
|
示例 1:
|
|
输入: nums = [1,3,5,6], target = 5
|
|
输出: 2
|
|
|
|
示例 2:
|
|
|
|
输入: nums = [1,3,5,6], target = 2
|
|
输出: 1
|
|
|
|
*/
|
|
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
int searchInsert(vector<int>& nums, int target) {
|
|
int low = 0, high = nums.size() - 1;
|
|
while (low <= high) {
|
|
int mid = (high - low) / 2 + low;
|
|
int num = nums[mid];
|
|
if (num == target) {
|
|
return mid;
|
|
} else if (num > target) {
|
|
high = mid - 1;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
return low;
|
|
}
|
|
int main() { return 0; } |