题目描述
统计一个数字在排序数组中出现的次数
思路:用二分法分别查找数字在数组中出现的开头和结尾的位置,次数=结尾-开头+1,时间复杂度为O(logn)
1 class Solution { 2 public: 3 int getFirstK(vector<int> &data, int k) 4 { 5 int begin=0; 6 int end=data.size()-1; 7 int mid; 8 while(begin<=end) 9 { 10 mid=(begin+end)/2; 11 if(data[mid]==k && mid==0)return mid; 12 else if(data[mid]==k && data[mid-1]!=k)return mid; 13 else if(data[mid]>=k)end=mid-1; 14 else begin=mid+1; 15 } 16 return -1; 17 } 18 int getLastK(vector<int> &data, int k) 19 { 20 int begin=0; 21 int end=data.size()-1; 22 int mid; 23 while(begin<=end) 24 { 25 mid=(begin+end)/2; 26 if(data[mid]==k && mid==data.size()-1)return mid; 27 else if(data[mid]==k && data[mid+1]!=k)return mid; 28 else if(data[mid]<=k)begin=mid+1; 29 else end=mid-1; 30 } 31 return -1; 32 } 33 int GetNumberOfK(vector<int> data ,int k) { 34 if(data.size()==0)return 0; 35 int first=getFirstK(data, k); 36 int last=getLastK(data, k); 37 if(first==-1 || last==-1)return 0; 38 return last-first+1; 39 } 40 };