35. Search Insert Position (Array; Divide-and-Conquer)
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
思路:排好序的数列用二分法进行搜索。二分法查找到的最后那个元素,要么是target,要么是紧邻target左侧或右侧的元素。
class Solution { public: int searchInsert(vector<int>& nums, int target) { if(nums.size()==0) return 0; return binarySearch(nums,0,nums.size()-1,target); } int binarySearch(vector<int>& nums, int start, int end, int target){ if(start==end){ if(target <= nums[start]) return start; else return start+1; } int mid = start + ((end-start)>>1); if(target <= nums[mid]) return binarySearch(nums,start,mid,target); else return binarySearch(nums,mid+1,end,target); } };