题目:
统计一个数字在排序数组中出现的次数。如, 输入排序数组{1, 2, 3, 3, 3, 3, 3, 4, 5} 和数字3,由于3在数组中出现4次,因此输出4.
在牛客网上做的测试。
第一版(正确):
int GetNumberOfK(vector<int> data ,int k) {
int i = 0;
for (auto x: data) {
if (x == k) {
i++;
}
}
return i;
}
第二版(错误) :
class
Solution {
public
:
int
GetNumberOfK(vector<
int
> data,
int
k) {
int
first = GetFirstK(data, k, 0, data.size() - 1);
if
(first == -1)
return
0;
int
last = GetLastK(data, k, first, data.size() - 1);
if
(last == -1)
return
0;
return
(last - first + 1);
}
int
GetFirstK(
const
vector<
int
>& data,
int
k,
int
begin,
int
end) {
cout <<
"Get Fist K: begin:"
<< begin <<
" end:"
<< end << endl;
if
(begin > end) {
return
-1;
}else if(begin == end) {
return begin;
}
int
mid = (begin + end) / 2;
if
(data[mid] > k) {
return
GetFirstK(data, k, begin, mid - 1);
}
else
if
(data[mid] == k) {
return GetFirstK(data, k, begin, mid);
}
else
{
return
GetFirstK(data, k, mid + 1, end);
}
}
int
GetLastK(
const
vector<
int
>& data,
int
k,
int
begin,
int
end) {
cout <<
"Get Last K: begin:"
<< begin <<
" end:"
<< end << endl;
if
(begin > end) {
return
-1;
} else if(begin == end) {
return begin;
}
int
mid = (begin + end) / 2;
if
(data[mid] > k) {
return
GetLastK(data, k, begin, mid - 1);
}
else
if
(data[mid] == k) {
return GetLastK(data, k, mid, end);
}
else
{
return
GetLastK(data, k, mid + 1, end);
}
}
第三版(正确):
class
Solution {
public
:
int
GetNumberOfK(vector<
int
> data,
int
k) {
if
(data.size() == 0) {
return
0;
}
int
first = GetFirstK(data, k, 0, data.size() - 1);
if
(first == -1)
return
0;
int
last = GetLastK(data, k, first, data.size() - 1);
return
(last - first + 1);
}
int
GetFirstK(
const
vector<
int
>& data,
int
k,
int
begin,
int
end) {
if
(begin > end) {
return
-1;
}
int
mid = (begin + end) / 2;
int
value = data[mid];
if
(value > k) {
end = mid - 1;
}
else
if
(value == k) {
if
(begin == mid || data[mid - 1] != k)
{
return
mid;
}
else
{
end = mid - 1;
}
}
else
{
begin = mid + 1;
}
return
GetFirstK(data, k, begin, end);
}
int
GetLastK(
const
vector<
int
>& data,
int
k,
int
begin,
int
end) {
if
(begin > end) {
return
-1;
}
int
mid = (begin + end) / 2;
int
value = data[mid];
if
(value > k) {
end = mid - 1;
}
else
if
(value == k) {
if
(mid == end || data[mid + 1] != k)
{
return
mid;
}
else
{
begin = mid + 1;
}
}
else
{
begin = mid + 1;
}
return
GetLastK(data, k, begin, end);
}
};