反正不想用递归
但是一说是排序的 最好又用二分查找,这样比较快;
方法一 :找出重复数字出现第一次的坐标。以及出现最后一次的坐标;
链接:https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2?f=discussion 来源:牛客网 class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int lower = getLower(data,k); int upper = getUpper(data,k); return upper - lower + 1; } //获取k第一次出现的下标 int getLower(vector<int> data,int k){ int start = 0,end = data.size()-1; int mid = (start + end)/2; while(start <= end){ if(data[mid] < k){ start = mid + 1; }else{ end = mid - 1; } mid = (start + end)/2; } return start; } //获取k最后一次出现的下标 int getUpper(vector<int> data,int k){ int start = 0,end = data.size()-1; int mid = (start + end)/2; while(start <= end){ if(data[mid] <= k){ start = mid + 1; }else{ end = mid - 1; } mid = (start + end)/2; } return end; } };
方法二: 利用一点小技巧
链接:https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2?f=discussion 来源:牛客网 //因为data中都是整数,所以可以稍微变一下,不是搜索k的两个位置,而是搜索k-0.5和k+0.5 //这两个数应该插入的位置,然后相减即可。 class Solution { public: int GetNumberOfK(vector<int> data ,int k) { return biSearch(data, k+0.5) - biSearch(data, k-0.5) ; } private: int biSearch(const vector<int> & data, double num){ int s = 0, e = data.size()-1; while(s <= e){ int mid = (e - s)/2 + s; if(data[mid] < num) s = mid + 1; else if(data[mid] > num) e = mid - 1; } return s; } };