剑指offer-37:数字在排序数组中出现的次数
目录
1问题描述
统计一个数字在排序数组中出现的次数。
2问题答案
看见有序,肯定就是二分查找了,算法比较简单,不多说
值得一提的是,不要拘泥于递归,要会循环写法。
class Solution {
/*二分查找 找到第一个K 和 最后一个K 二者位置相减*/
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.empty())
return 0;
int number = 0;
int first = GetFirstIndex(data,k,0,data.size()-1);
int last = GetLastIndex(data,k,0,data.size()-1);
if(first>-1 && last>-1)
number = last - first +1;
return number;
}
int GetFirstIndex(vector<int> &data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid] == k){
if((mid == start) || (data[mid-1] != k))
return mid;
else
end = mid-1;
}
else{
if(data[mid] > k)
end = mid - 1;
else
start = mid + 1;
}
return GetFirstIndex(data,k,start,end);
}
int GetLastIndex(vector<int> &data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid]==k){
if((mid == end) || (data[mid+1] != k))
return mid;
else
start = mid +1;
}
else{
if(data[mid]>k)
end = mid-1;
else
start = mid+1;
}
return GetLastIndex(data,k,start,end);
}
};
3完整代码
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.empty())
return 0;
int number = 0;
int first = GetFirstIndex(data,k,0,data.size()-1);
int last = GetLastIndex(data,k,0,data.size()-1);
if(first>-1 && last>-1)
number = last - first +1;
return number;
}
int GetFirstIndex(vector<int> &data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid] == k){
if((mid == start) || (data[mid-1] != k))
return mid;
else
end = mid-1;
}
else{
if(data[mid] > k)
end = mid - 1;
else
start = mid + 1;
}
return GetFirstIndex(data,k,start,end);
}
int GetLastIndex(vector<int> &data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid]==k){
if((mid == end) || (data[mid+1] != k))
return mid;
else
start = mid +1;
}
else{
if(data[mid]>k)
end = mid-1;
else
start = mid+1;
}
return GetLastIndex(data,k,start,end);
}
};
int main()
{
cout<<"number of K : "<<endl;
Solution s;
vector<int> a={1,2,3,4,4,5,6,7,8,9,9,9,10};
cout<<s.GetNumberOfK(a,9)<<endl;
}
number of K :
3