Topic:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume no duplicates in the array.
Here is 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
Idea: Using two-point search
<pre name= "code" class= "CPP" > #include <iostream> #include <vector>using namespace std;/* Find an element in an orderly array the appropriate insertion position can be found using a binary lookup */int insertpos (vector<int>& vec,int key) {int mid,begin=0,end = Vec.size () -1;while (begin<=end) {mid = begin + (end-begin)/2;if (vec[mid] = = key) return Mid;else if (Vec[mid] < key) begin = Mid+1;elseend = Mid-1;} return mid >=vec.size () -1?vec.size (): Mid;} int main () {int array[]={1,8,9,12,15};vector<int> Vec (array,array+sizeof (array)/sizeof (int));cout<< Insertpos (vec,100); return 0;}
Search Insert Position--leetcode