35. Search Insert Position
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0,high = nums.size()-1;
while(low <= high){
int mid = low + (high-low)/2;
if(target > nums[mid])
low = mid + 1;
else
high = mid - 1;
}
return low;
}
};
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.empty())
return 0;
int start=0,end=nums.size()-1;
while(start+1<end){
int mid=(end-start)/2+start;
if(nums[mid]==target)
return mid;
else if(nums[mid]<target)
start=mid;
else
end=mid;
}
if(nums[start]==target)
return start;
else if(nums[end]==target)
return end;
else if(nums[end]<target)
return end+1;
else if(nums[start]>target)
return start>0?start-1:0;
else
return end;
}
};