Problem 91
Search Insert Position
Easy · 10 pts · Array, Binary Search
Problem
You are given an array of N distinct integers sorted in increasing order, and a target T. If T is in the array, print its index. If it is not, print the index where T would have to be inserted to keep the array sorted. Use zero-based indexing. Both cases ask for the same thing: the first index whose value is greater than or equal to T (or N if every value is smaller). Binary search finds it in O(log N).
Input
First line: integers N and T. Second line: N distinct integers in increasing order.
Output
Print the zero-based index.
Constraints
1 <= N <= 100000; -1000000000 <= A[i], T <= 1000000000
Example input
4 5 1 3 5 6
Example output
2
Explanation
In 1 3 5 6, the target 5 is present at index 2, so the answer is 2. If the target had been 2, it would belong between 1 and 3, at index 1.