给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
#include <iostream>
#include <vector>int searchInsert(std::vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) {return mid;} else if (nums[mid] < target) {left = mid + 1;} else {right = mid - 1;}}return left;
}int main() {std::vector<int> nums = {1, 3, 5, 6};int target = 5;int result = searchInsert(nums, target);std::cout << "Target value " << target << " should be inserted at index " << result << std::endl;return 0;
}
函数使用二分查找的方法,在数组中找到目标值的索引,如果目标值不存在,则返回应该插入的位置
使用的算法是二分查找,其时间复杂度为 O(log n),其中 n 为数组的长度。这是因为每次迭代都将搜索范围减半,直到找到目标值或确定插入位置。
空间复杂度方面,代码只使用了常数级别的额外空间,因此空间复杂度为 O(1)。