Last active
September 28, 2019 17:18
-
-
Save nderkach/f7b46e214bdd3b4d15a42e74d1ec029f to your computer and use it in GitHub Desktop.
Given a sorted bit array (values of either 0 or 1), determine the number of 1’s in the 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
//Given a sorted bit array (values of either 0 or 1), determine the number of 1’s in the array. | |
// | |
//Perform this in O(log(N)) time complexity. | |
// | |
//Input: [0,0,0,1,1,1,1,1,1,1,1] | |
// | |
//Output: 8 | |
func numOnes(_ arr: [Int]) -> Int { | |
func binSearch(left: Int, right: Int) -> Int { | |
var left = left, right = right | |
while (left + 1 < right) { | |
let middle = (left + right) / 2 | |
if arr[middle] == arr[right] { | |
right = middle | |
} else { | |
left = middle | |
} | |
} | |
return right | |
} | |
let firstOneIdx = binSearch(left: 0, right: arr.count - 1) | |
return arr.count - firstOneIdx | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment