Given a sorted array, find how many times a specified element appears.
Anonymous
One way it to do binary search and look left and right to find number of items. Other way is to do two binary search. One establishes arr[i] =X and other etablishes arr[i] X. The number of items is difference of these two indexes. public static int numEquals(int[] arr, int num) { if(arr.length = X for(; i + 1 != j;){ int k = (i + j) / 2; if (arr[k] X if (arr[len-1] == num) return len - i; for(left = j, j = len; i + 1 != j;){ int k = (i + j) / 2; if (arr[k] <= num) i = k; else j = k; } return j - left; }
Check out your Company Bowl for anonymous work chats.