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 start = 0, end = nums.size() - 1;
if (nums.empty()) {
return 0;
}
while (start <= end) {
if (start == end) {
if (nums[start] == target) {
return start;
}
}
int harve = (start + end) / 2;
if (nums[harve] < target) {
start = harve+1;
}
else if(nums[harve]>target){
end = harve-1;
}
else {
return harve;
}
}
if (end < 0) return 0;
if (nums[end] > target) {
return end;
}
else return end+1;
//return search;
}
};