1. 程式人生 > >劍指Offer - 數字在排序數組中出現的次數

劍指Offer - 數字在排序數組中出現的次數

turn -- class vector ++ esc data bject ber

https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tqId=11190&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述

統計一個數字在排序數組中出現的次數。
class Solution {
    int findK(vector<int> &data ,int k) {
        int first = 0;
        
int last = data.size() - 1; while (first <= last) { int mid = first + (last - first) / 2; if (data[mid] == k) return mid; else if (data[mid] < k) first = mid + 1; else last = mid - 1; } return -1; } public:
int GetNumberOfK(vector<int> data ,int k) { if (data.size() == 0) return 0; int idx = findK(data, k); if (idx == -1) return 0; int first = idx, last = idx; while (first >= 0 && data[first] == data[idx]) first--; while (last < data.size() && data[last] == data[idx]) last++;
return last - first -1; } };

劍指Offer - 數字在排序數組中出現的次數