思路1:該解法是最直觀的解法,可以先使用二分查找先找到這個元素,然後分別向左和向右遍歷,把左右相同的元素的個數都計算出來。
思路2:使用二分查找的拓展,當查找的元素有重復的時,找到元素的第一個和最後一個,這樣將可以計算出該元素有多少個重復的了。
1 #include <stdio.h> 2 #include "stdafx.h" 3 4 int GetFirstK(int* data, int length, int k, int start, int end); 5 int GetLastK(int* data, int length, int k, int start, int end); 6 7 int GetNumberOfK(int* data, int length, int k) 8 { 9 int number = 0; 10 11 if(data != NULL && length > 0) 12 { 13 int first = GetFirstK(data, length, k, 0, length - 1); 14 int last = GetLastK(data, length, k, 0, length - 1); 15 16 if(first > - 1 && last > -1) 17 number = last - first + 1; 18 } 19 20 return number; 21 } 22 23 int GetFirstK(int* data, int length, int k, int start, int end) 24 { 25 if(start > end) 26 return -1; 27 28 int middleIndex = (start + end) / 2; 29 int middleData = data[middleIndex]; 30 31 if(middleData == k) 32 { 33 if((middleIndex > 0 && data[middleIndex - 1] != k) || middleIndex == 0) 34 return middleIndex; 35 else 36 end = middleIndex -1; 37 } 38 else if(middleData > k) 39 end = middleIndex - 1; 40 else 41 start = middleIndex + 1; 42 43 return GetFirstK(data, length, k, start , end); 44 45 } 46 47 int GetLastK(int* data, int length, int k, int start, int end) 48 { 49 if(start > end) 50 return -1; 51 52 int middleIndex = (start + end) /2 ; 53 int middleData = data[middleIndex]; 54 55 if(middleData == k) 56 { 57 if((middleIndex < length - 1 && data[middleIndex + 1] != k ) || middleIndex == length - 1) 58 return middleIndex; 59 else 60 start = middleIndex + 1; 61 } 62 else if(middleData < k) 63 start = middleIndex + 1; 64 else 65 end = middleIndex - 1; 66 67 return GetLastK(data, length, k, start, end); 68 } 69 70 int main() 71 { 72 int data[] = {1,2,3,3,3,3,4,5}; 73 int length = sizeof(data) / sizeof(int); 74 int k = 3; 75 for(int i = 0; i < length; ++i) 76 printf("%d\t", data[i]); 77 printf("\n"); 78 int result = GetNumberOfK(data, length, k); 79 printf("%d出現%d次\n",k,result); 80 81 return 0; 82 }