https://leetcode.com/problems/search-insert-position/description/
int search(vector<int>& nums, int target, int lo, int hi) {
if(lo + 1 == hi && target > nums[lo] && target <= nums[hi]) return hi;
int mid = (lo + hi)/2;
if(nums[mid] == target) return mid;
if(target < nums[mid]) return search(nums, target, lo, mid);
if(target > nums[mid]) return search(nums, target, mid, hi);
}
int searchInsert(vector<int>& nums, int target) {
if(target<=nums[0]) return 0;
if(target>nums.back()) return nums.size();
return search(nums, target, 0, nums.size()-1);
}
No comments:
Post a Comment