- /************************************************************************/
- /* 10、在排序数组中,找出给定数字出现的次数 */
- /************************************************************************/
- //二分查找,二分查找key第一次出现的位置,二分查找最后一次出现的key
- //返回两者相减+1或者找到第一次出现的位置,向后查找
- int binarySearchFirstPos(int * iArr, int l, int h, int key)
- {
- while(l <= h )
- {
- int mid = (l + h) / 2;
- if(iArr[mid] < key)
- l = mid +1;
- else if(iArr[mid] > key)
- h = mid - 1;
- else
- {
- if(mid == l || iArr[mid - 1] != key)
- return mid;
- else
- h = mid - 1;
- }
- }
- return -1;
- }
- int binarySearchLastPos(int * iArr, int l, int h, int key)
- {
- while(l <= h)
- {
- int mid = (l + h) / 2;
- if(iArr[mid] < key)
- l = mid + 1;
- else if(iArr[mid] > key)
- h = mid - 1;
- else
- {
- if(mid == h || iArr[mid + 1] != key)
- return mid;
- else
- l = mid + 1;
- }
- }
- return -1;
- }
- int numOfKey(int * iArr, int length, int key)
- {
- int firstPos = binarySearchFirstPos(iArr, 0, length - 1, key);
- int lastPos = binarySearchLastPos(iArr, 0, length - 1, key);
- cout << firstPos << "\t" << lastPos << endl;;
- if(firstPos == -1)
- return 0;
- else
- return lastPos - firstPos + 1;
- }
在排序数组中,找出给定数字出现的次数
最新推荐文章于 2020-09-18 22:59:05 发布