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
Subscribe to see which companies asked this question
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = 0, r = nums.size()-1, pos=-1;
while(l <= r) {
int mid = (l+r)/2;
if(nums[mid] == target) {
pos = mid;
break;
} else if(nums[mid] > target) {
r = mid-1;
} else {
l = mid+1;
}
}
if(l <= r) return pos;
else return l;
}
}
本文介绍了一个算法问题:在已排序的数组中查找目标值的索引,若不存在则返回目标值按序插入的位置。该算法使用了二分查找的方法来高效定位目标值或其合适的插入位置。
525

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



