题目:统计一个数字在排序数组中出现的次数。例如,输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4.
思路1:该解法是最直观的解法,可以先使用二分查找先找到这个元素,然后分别向左和向右遍历,把左右相同的元素的个数都计算出来。
思路2:使用二分查找的拓展,当查找的元素有重复的时,找到元素的第一个和最后一个,这样将可以计算出该元素有多少个重复的了。
#include <stdio.h>
#include "stdafx.h"
int GetFirstK(int* data, int length, int k, int start, int end);
int GetLastK(int* data, int length, int k, int start, int end);
int GetNumberOfK(int* data, int length, int k)
{
int number = 0;
if(data != NULL && length > 0)
{
int first = GetFirstK(data, length, k, 0, length - 1);
int last = GetLastK(data, length, k, 0, length - 1);
if(first > - 1 && last > -1)
number = last - first + 1;
}
return number;
}
int GetFirstK(int* data, int length, int k, int start, int end)
{
if(start > end)
return -1;
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if(middleData == k)
{
if((middleIndex > 0 && data[middleIndex - 1] != k) || middleIndex == 0)
return middleIndex;
else
end = middleIndex -1;
}
else if(middleData > k)
end = middleIndex - 1;
else
start = middleIndex + 1;
return GetFirstK(data, length, k, start , end);
}
int GetLastK(int* data, int length, int k, int start, int end)
{
if(start > end)
return -1;
int middleIndex = (start + end) /2 ;
int middleData = data[middleIndex];
if(middleData == k)
{
if((middleIndex < length - 1 && data[middleIndex + 1] != k ) || middleIndex == length - 1)
return middleIndex;
else
start = middleIndex + 1;
}
else if(middleData < k)
start = middleIndex + 1;
else
end = middleIndex - 1;
return GetLastK(data, length, k, start, end);
}
int main()
{
int data[] = {1,2,3,3,3,3,4,5};
int length = sizeof(data) / sizeof(int);
int k = 3;
for(int i = 0; i < length; ++i)
printf("%d\t", data[i]);
printf("\n");
int result = GetNumberOfK(data, length, k);
printf("%d出现%d次\n",k,result);
return 0;
}