Skip to content

Instantly share code, notes, and snippets.

@ChenCodes
Created January 3, 2017 01:27
Show Gist options
  • Save ChenCodes/aa73f2d4fca8f3352312167f4adcb2a4 to your computer and use it in GitHub Desktop.
Save ChenCodes/aa73f2d4fca8f3352312167f4adcb2a4 to your computer and use it in GitHub Desktop.
func countOccurrencesOfKey(_ key: Int, inArray a: [Int]) -> Int {
func leftBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] < key {
low = midIndex + 1
} else {
high = midIndex
}
}
return low
}
func rightBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] > key {
high = midIndex
} else {
low = midIndex + 1
}
}
return low
}
return rightBoundary() - leftBoundary()
}
let a = [ 0, 1, 1, 3, 3, 3, 3, 6, 8, 10, 11, 11 ]
print(countOccurrencesOfKey(3, inArray: a)) // returns 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment