Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目大意:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
实现思路:
很简单的二分查找。
实现代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int end=nums.size();
int start=0;
int mid=(start+end)/2;
while(start<=end){
mid=(start+end)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target){
if(mid<=0||nums[mid-1]<target) return mid;
end=mid-1;
}
else if(nums[mid]<target){
if(mid>=(nums.size()-1)||nums[mid+1]>target) return (mid+1);
start=mid+1;
}
}
return nums.size();
}
};
写的略有些繁琐
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int l=0,r=n-1;
while(l<=r){
int mid=l+(r-l)/2;
if(nums[mid]<target)
l=mid+1;
else r=mid-1;
}
return l;
}
};
这个简单了不少,但可以优化一下,加个终止条件
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int l=0,r=n-1;
while(l<=r){
int mid=l+(r-l)/2;
if(nums[mid]==target) return mid;
if(nums[mid]<target)
l=mid+1;
else r=mid-1;
}
return l;
}
};