二分查找基本框架 (返回target,返回left,返回right)

 /* 返回target所在的位置

    int binary_search(vector<int> nums,int target)

    {

        int left = 0;

        int right = nums.size();

        while(left <= right)

        {

            int mid = left + (right - left) / 2;

            if(nums[mid] == target)

            {

                return mid;

            }else if(nums[mid] < target)

            {

                left = mid + 1;

            }else if(nums[mid] > target)

            {

                right = mid - 1;

            }

        }

        return -1;

    } */

 

/*  返回左侧的边界

    int binary_search(vector<int> nums,int target)

    {

        int left = 0;

        int right = nums.size();

        while(left <= right)

        {

            int mid = left + (right - left) / 2;

            if(nums[mid] == target)

            {

                right = mid - 1;

            }else if(nums[mid] < target)

            {

                left = mid + 1;

            }else if(nums[mid] > target)

            {

                right = mid - 1;

            }

        }

        if(left > nums.size()||nums[left] != target)

            return -1;

        return left;

    } */

/* 返回右侧的边界

int binary_search(vector<int> nums, int target)

{

    int left = 0;

    int right = nums.size();

    while (left <= right)

    {

        int mid = left + (right - left) / 2;

        if (nums[mid] == target)

        {

            left = mid + 1;

        }

        else if (nums[mid] < target)

        {

            left = mid + 1;

        }

        else if (nums[mid] > target)

        {

            right = mid - 1;

        }

    }

    if (right < 0 || nums[right] != target)

        return -1;

    return right;

    } */

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页