Created
June 13, 2019 23:25
-
-
Save jasonwaters/1c0cf3b4273a491e9cdb052b3b5af5a6 to your computer and use it in GitHub Desktop.
Count the number of repeat integers in a sorted array.
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
function first(arr, target, left, right, found=-1) { | |
const mid = Math.floor((left+right)/2); | |
found = arr[mid] === target ? mid : found; | |
if(right > left) { | |
if(arr[mid] >= target) { | |
return first(arr, target, left, mid-1, found); | |
}else if(arr[mid] < target) { | |
return first(arr, target, mid+1, right, found); | |
} | |
} | |
return found; | |
} | |
function last(arr, target, left, right, found=-1) { | |
const mid = Math.floor((left+right)/2); | |
found = arr[mid] === target ? mid : found; | |
if(right > left) { | |
if(arr[mid] > target) { | |
return last(arr, target, left, mid-1, found); | |
}else if(arr[mid] <= target) { | |
return last(arr, target, mid+1, right, found); | |
} | |
} | |
return found; | |
} | |
function countDupes(arr, target) { | |
const left = first(arr, target, 0, arr.length); | |
const right = last(arr, target, left, arr.length); | |
const count = left >= 0 ? right-(left-1) : 0; | |
return count; | |
} | |
const arr = [1,2,3,3,3,3,4,5,6,7,7,7,7,9,9]; | |
// const arr = [1,2,2,2,3]; | |
new Set(arr).forEach((value) => { | |
const dupes = countDupes(arr, value); | |
console.log(`value: ${value}, dupes: ${dupes}`) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment