2023.9.4
本题较为简单,题目要求O(log n)的时间复杂度,就不能遍历查找了,得用二分查找。若成功查找到target值,则直接返回索引; 若直到结束都没查找到则返回left值。(纸上模拟下就懂了)
代码如下:
class Solution {
public:int searchInsert(vector<int>& nums, int target) {int left = 0;int right = nums.size()-1;while(left <= right){int mid = (left + right) / 2;if(nums[mid] == target) return mid;else if(nums[mid] < target) left = mid + 1;else right = mid - 1; }return left;}
};