Created
January 3, 2017 01:27
-
-
Save ChenCodes/aa73f2d4fca8f3352312167f4adcb2a4 to your computer and use it in GitHub Desktop.
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
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