Given a sorted array 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 may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i = 0, j = nums.size()-1;
if(target <= nums[0]) return 0;
if(target > nums[j]) return j+1;
while(i < j){
int mid = (i + j) / 2;
if(nums[mid] < target)
i = mid + 1;
else j = mid;
}
return i;
}
};
本文介绍了一个查找并返回目标值在已排序数组中应插入位置的算法。该算法假设数组无重复元素,并通过二分查找确定目标值的理想插入点。
242

被折叠的 条评论
为什么被折叠?



