Swift solution - Binary Search


  • 0
    class Solution {
        func hIndex(_ citations: [Int]) -> Int {
            let count = citations.count
            var left = 0
            var right = citations.count - 1
            var middle = 0
            
            while left <= right {
                middle = (left + right) >> 1
                if citations[middle] == (count - middle) {
                    return citations[middle]
                } else if citations[middle] > (count - middle) {
                    right = middle - 1
                } else {
                    left = middle + 1
                }
            }
            
            return count - (right + 1)
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.