Binary Search

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值