1.Easy binary search in a sort array without duplicate elements
int left=0;right=arr.size()-1;
while(left <= right)//<=
{
int mid = left + ((right-left)>>1);
int mid = left + (right - left) / 2;//avoid overflow
if(arr[mid] < key)
{
left = mid + 1;
}else if(arr[mid] > key)
{
right = mid - 1;
}else
return mid;
}
2.if the array has the duplicates element,we want to find the smallest index of target or not just return -1
Thinking:
a. If A[mid] < target, then leftmost target must begins on the right of mid (hence i = mid+1 for the next iteration)
b. If A[mid] > target, it means the leftmost must begins on the left of mid (j = mid-1)
c. If A[mid] = target, then the range must begins on the left of or at mid (j= mid)
int searchLeft(vector<int>& nums, int target) {
int i=0,j=nums.size()-1;
int mid=0;
//search for the left one
while(i<j)//watch the operator
{
mid=(i+j)/2;
if(nums[mid]<target)i=mid+1;
else if(nums[mid]>target)j=mid-1;//this line could omit
else j=mid;
}
if(nums[i]!=target)
return -1;
else return i;
}
3.when we want to search the rightmost target:
If A[mid] > target, then the rightmost must begins on the left of mid (j = mid-1)
If A[mid] < target, then the rightmost must begins on the right of mid (hence i = mid+1 for the next iteration)
If A[mid] = target, then the rightmost must begins on the right of or at mid (i= mid)
int searchRight(vector<int>& nums, int target) {
int i=0,j=nums.size()-1;
int mid=0;
//search for the right one
while(i<j)
{
mid=(i+j)/2+1;//thinking [5 7], target = 5
if(nums[mid]<target)i=mid+1;
else if(nums[mid]>target)j=mid-1;
else i=mid;
}
if(nums[i]!=target)
return -1;
else return i;
}
4.find the index where it would be if it were inserted in order.
For example :[1,3,5,6], 2 → 1
int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;
while (low <= high) {
int mid = low + (high-low)/2;
if (nums[mid] < target)
low = mid+1;
else
high = mid-1;
}
return low;
}