Interview question: How can I find the number of occurrences of a certain number of sorted arrays?
Answer: The fastest way is to first find the leftmost position of the number in the array, and then find the rightmost position of the number in the array. The difference between the two is what you want, the time complexity is logn.
The Code is as follows:
# Include <stdio. h> # include <stdlib. h> int bsearch_left (INT arr [], int L, int R, int v) {int left = L, Right = r; while (left <= right) {int mid = left + (right-left)/2; If (V> arr [Mid]) Left = Mid + 1; else right = mid-1 ;} if (ARR [left] = V) return left; else return-1;} int bsearch_right (INT arr [], int L, int R, int V) {int left = L, Right = r; while (left <= right) {int mid = left + (right-left)/2; If (v <arr [Mid]) right = mid-1; else left = Mid + 1 ;} If (ARR [right] = V) return right; else return-1;} int main () {int A [] = {1, 2, 2, 3, 3, 3, 5, 5}; int num = 1; int lindex = bsearch_left (A, num); int rindex = bsearch_right (A, num); If (lindex! =-1 & rindex! =-1) printf ("% d \ n", rindex-lindex + 1); else printf ("not found \ n"); System ("pause "); return 0 ;}