标签:
class Solution { public: int lowindex(vector<int>&data,int k,int low,int high) { if(low<high) { int i=low,j=high; int mid=(i+j)/2; if(data[mid]>k) return lowindex(data,k,low,mid-1); if(data[mid]<k) return lowindex(data,k,mid+1,high); if(data[mid]==k&&(mid==0||data[mid-1]!=k)) return mid; else return lowindex(data,k,low,mid-1); } else return low; } int highindex(vector<int>&data,int k,int low,int high) { if(low<high) { int i=low,j=high; int mid=(i+j)/2; if(data[mid]>k) return lowindex(data,k,low,mid-1); if(data[mid]<k) return lowindex(data,k,mid+1,high); if(data[mid]==k&&(mid==data.size()-1||data[mid+1]!=k)) return mid; else return highindex(data,k,mid+1,high); } else return low; } int GetNumberOfK(vector<int> data ,int k) { if(data.empty())return 0; int low =lowindex(data,k,0,data.size()-1); int high =highindex(data,k,0,data.size()-1); if(low==high&&data[low]!=k) return 0; int dis=high-low+1; return dis; } };
标签:
原文地址:http://www.cnblogs.com/daocaorenblog/p/5394797.html