Leetcode, SearchInsertPosition
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template<typename ForwardIter, typename T>
ForwardIter myLower_bound(ForwardIter first, ForwardIter last, T value)
{
while (first != last)
{
auto mid = next(first, distance(first, last) / 2);
if (value > *mid) first = ++mid;
else last = mid;
}
return first;
}
//时间复杂度O(logn),空间复杂度O(1)
int solution(int arr[], int n, int target)
{
return distance(arr, myLower_bound(arr, arr + n, target));
}
int main()
{
int arr[] = {1, 3, 5, 6};
cout << solution(arr, 4, 5) << endl; //2
cout << solution(arr, 4, 2) << endl; //1
cout << solution(arr, 4, 7) << endl; //4
cout << solution(arr, 4, 0) << endl; //0
return 0;
}