题目描述
统计一个数字在升序数组中出现的次数。
由于是有序数组所以采用了二分查找
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int count = 0; if(data.size()==0) return count; int low = 0; int high = data.size()-1; int mid; while(low<=high){ mid = low + (high - low) / 2; if(data[mid]==k) break; else if(data[mid] > k) high = mid-1; else low = mid +1; } if(low<=high){ count++; int i = mid-1; int j = mid+1; while(data[i]==k){ count++; i--; } while(data[j]==k){ count++; j++; } } return count; } };
使用STL库函数equal_range实现:
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { //也可以将pair<vector<int>::iterator, vector<int>::iterator >替换为auto pair<vector<int>::iterator, vector<int>::iterator > resultPair = equal_range(data.begin(), data.end(),k); return resultPair.second - resultPair.first; } };
equal_range函数解析:https://www.jianshu.com/p/edb6a7655976
使用STL库函数count实现:
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { return count(data.begin(),data.end(),k); } };
使用STL库函数low_bound、upper_bound实现:
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { auto start = lower_bound(data.begin(), data.end(), k); auto end = upper_bound(data.begin(),data.end(), k); return end - start; } };