題目:統計一個數字在排序數組中出現的次數。例如,輸入排序數組{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;
}