Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a sorted integer array of length n with possible duplicate elements. Find the number of occurrences of an integer k using binary search.
- Input format
- There are 2 lines of input.
- First line contains 2 space separated integers n, k - Number of elements, the integer k.
- Second line contains n space separated integers - The integer array.
- Output format
- Print the number of occurrences of the integer k.
- Sample Input 1
- 5 2
- -1 2 2 4 7
- Sample Output 1
- 2
- Explanation 1
- The integer 2 occurs 2 times in the given array.
- Constraints
- 1 <= n <= 10^6
- -10^9 <= k <= 10^9
- -10^9 <= A[i] <= 10^9
- */
- /**
- * @param {number} n
- * @param {number} target
- * @param {number[]} arr
- * @return {number}
- */
- function countOccurrences(n, target, arr) {
- // let n = arr.length;
- let low=0;
- let high=n-1;
- let foundIndexOfTarget=-1;
- let startingIndex=-1;
- let endingIndex=-1;
- while(low<=high){
- let mid=Math.floor((low+high)/2);
- if(target==arr[mid]){
- foundIndexOfTarget=mid;
- break;
- }
- else if(target>arr[mid]){
- low=mid+1;
- }
- else{
- high=mid-1;
- }
- }
- // console.log(`foundIndexOfTarget ${foundIndexOfTarget}`);
- if(foundIndexOfTarget==-1)
- return 0;
- // getting startting Left index
- low=0;
- high=foundIndexOfTarget;
- while(low<=high){
- let mid=Math.floor((low+high)/2);
- // condition
- if((mid!=0&&arr[mid]==target&&arr[mid]>arr[mid-1])
- ||(mid==0&&arr[mid]==target)
- ){
- startingIndex=mid;
- break;
- }
- if(arr[mid]<target){
- low=mid+1;
- }
- else{
- high=mid-1;
- }
- }
- // getting endingIndex
- low=foundIndexOfTarget;
- high=n-1;
- while(low<=high){
- let mid=Math.floor((low+high)/2);
- if((mid!=n-1&&arr[mid]==target&&arr[mid]<arr[mid+1])
- ||(mid==n-1&&arr[mid]==target)
- ){
- endingIndex=mid;
- break;
- }
- if(target<arr[mid]){
- high=mid-1;
- }
- else{
- low=mid+1;
- }
- }
- return endingIndex-startingIndex+1;
- }
- function main() {
- let [n, k] = readIntArr();
- let arr = readIntArr();
- let ans = countOccurrences(n, k, arr);
- print(ans);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement