Swift solution - Binary Search


  • 0
    class Solution {
        func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
            let start = binarySearch(nums, target)
            
            if start == nums.count || nums[start] != target {
                return [-1, -1]
            }
            
            let end = binarySearch(nums, target + 1) - 1
            
            return [start, end]
        }
        
        private func binarySearch(_ nums: [Int], _ target: Int) -> Int {
            var left = 0
            var right = nums.count
            var middle = 0
            
            while left < right {
                middle = (left + right) / 2
                if nums[middle] < target {
                    left = middle + 1
                } else {
                    right = middle
                }
            }
            
            return left
        }
    }
    

Log in to reply
 

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