剑指offer二分53-I. 在排序数组中查找数字

Posted trevo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer二分53-I. 在排序数组中查找数字相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/

二分

时间复杂度:O(logn)
空间复杂度:O(1)

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size() - 1;
        int l = 0;
        int r = n + 1;
        while(l < r)
        {
            int mid = l + r >> 1;
            //找到第一个大于等于target的位置
            if(nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        //cout << r << endl;
        int res = 0;
        int i = l;
        while(i <= n && nums[i++] == target)
            res++;
        return res;
    }
};

以上是关于剑指offer二分53-I. 在排序数组中查找数字的主要内容,如果未能解决你的问题,请参考以下文章