剑指-27.数组在排序数组中的出现次数

class Solution {
public:
    int GetNumberOfK(vector data ,int k) {
        //碰到先排序,后二分
        //边界条件
        if(data.empty()) return 0;
        //找K-0.4~K+0.6的范围
        return findK(data,k+0.6)-findK(data,k-0.4);
    }
 private:
    int findK(vector data ,int k)
 {
     sort(data.begin(),data.end());
        int low=0,high=data.size()-1;
        while (low<=high)
        {
            int mid=low+(high-low)/2;
            if(data[mid]<=k)
                low=mid+1;
            else 
                high=mid-1;
        }
        return low;
 }
};

 

你可能感兴趣的:(剑指-27.数组在排序数组中的出现次数)