数字在排序数组中出现的次数

你快乐吗?

Posted by bbkgl on September 26, 2019

数字在排序数组中出现的次数

C++,二分。

class Solution {
public:
    int GetNumberOfK(vector<int> data ,int k) {
        int index = Find(data, k);
        if (index == -1) return 0;
        int left = index, right = index;
        for (; left >= 0 && data[left] == k; left--) ;
        for (; right < data.size() && data[right] == k; right++) ;
        return right - left - 1;
    }
    
    int Find(vector<int> &data, int &k) {
        int ans = -1;
        int left = 0, right = data.size() - 1;
        int mid = (left + right) / 2;
        while (left <= right) {
            mid = (left + right) / 2;
            if (k > data[mid])
                left = mid + 1;
            else if (k < data[mid])
                right = mid - 1;
            else {
                ans = mid;
                break;
            }
        }
        return ans;
    }
};