Created
February 13, 2014 11:04
-
-
Save jack-wong-build/8973264 to your computer and use it in GitHub Desktop.
Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1,2,3,4,4,4,4,4,5,6,7 | |
function findFrequency(array, target){ | |
var first, last; | |
var result = -1; | |
first = findFirst(array, target, 0, array.length-1); | |
if (first !== -1){ | |
last = findLast(array, target, 0, array.length-1); | |
result = last - first + 1; | |
} | |
return result; | |
} | |
function findFirst(array, target, startIndex, lastIndex){ | |
// base case | |
if (startIndex ===lastIndex){ | |
if (target === array[startIndex]){ | |
return startIndex; | |
} else{ | |
return -1; | |
} | |
} | |
var mediumIndex = startIndex + Math.floor( (lastIndex - startIndex ) / 2 ); | |
if (target <= array[mediumIndex]){ | |
return findFirst(array, target, startIndex, mediumIndex); | |
} else { | |
return findFirst(array, target, mediumIndex + 1, lastIndex); | |
} | |
} | |
function findLast(array, target, startIndex, lastIndex){ | |
// base case | |
if (startIndex ===lastIndex){ | |
if (target === array[startIndex]){ | |
return startIndex; | |
} else{ | |
return -1; | |
} | |
} | |
var mediumIndex = startIndex + Math.floor( (lastIndex - startIndex ) / 2 ); | |
if (target >= array[mediumIndex + 1]){ | |
return findLast(array, target, mediumIndex + 1, lastIndex); | |
} else { | |
return findLast(array, target, startIndex, mediumIndex); | |
} | |
} | |
console.log( findFrequency([1,2,3,4,4,4,4,5,5,6,7], 5) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment