剑指offer 53:在排序数组中查找数字

在这里插入图片描述
思路
二次二分查找,查找target的右边界和target-1的右边界。target-1存在与否不影响边界的查找,可以理解成搜索插入位置。二者相减即为target出现的次数

class Solution {
    
    
public:
    int rightBound(vector<int>& nums, int target) {
    
    
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
    
    
            int mid = l + (r - l)/2;
            if (nums[mid] == target) l = mid + 1;
            else if (nums[mid] > target) r = mid - 1;
            else if (nums[mid] < target) l = mid + 1;
        }
        return r;
    }
    int search(vector<int>& nums, int target) {
    
    
        return rightBound(nums, target) - rightBound(nums, target-1);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114166800