标签:
“沟通、学习能力就是看面试者能否清晰、有条理地表达自己,是否会在自己所得到的信息不够的情况下主动发问澄清,能否在得到一些暗示之后迅速做出反应纠正错误” ---陈黎明(MSoft-SDE)#include <iostream> using namespace std; int arr[8]={1,2,3,3,3,3,4,5}; int GetFirstK(int *array,int k,int length,int start ,int end) { if(start>end) return -1; int middleIndex=(start+end)/2; int middledata=array[middleIndex]; if(middledata==k) { if(middleIndex>0 && array[middleIndex-1]!=k || middleIndex==0) return middleIndex; else end=middleIndex-1; } else if(middledata>k) end=middleIndex-1; else start=middleIndex+1; return GetFirstK(array,k,length,start,end); } int GetLastK(int *array,int k,int length,int start,int end) { if(start>end) return -1; int middleIndex=(start+end)/2; int middledata=array[middleIndex]; if(middledata==k) { if(middleIndex<length-1 && array[middleIndex+1]!=k || middleIndex==length-1) return middleIndex; else start=middleIndex+1; } else if(middledata>k) end=middleIndex-1; else start=middleIndex+1; return GetLastK(array,k,length,start,end); } int GetNumK(int *array,int length,int k) { int number=0; if(array!=NULL && length>0) { int first=GetFirstK(array,k,length,0,length-1); int last=GetLastK(array,k,length,0,length-1); if(first>-1 && last>-1) number=last-first+1; else return 0; } return number; } int main() { int num=GetNumK(arr,8,3); cout<<"3出现的次数是:"<<num<<endl; system("pause"); return 0; }
运行结果是:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51712624