Swift solution - Binary Search


  • 0
    class Solution {
        func search(_ nums: [Int], _ target: Int) -> Int {
            if nums.count == 0 {
                return -1
            }
            
            var left = 0
            var right = nums.count - 1
            var middle = 0
            
            while left < right {
                middle = (left + right) / 2
                if nums[middle] == target {
                    return middle
                }
                if nums[left] <= nums[middle] {
                    if target >= nums[left] && target < nums[middle] {
                        right = middle - 1
                    } else {
                        left = middle + 1
                    }
                } else {
                    if target > nums[middle] && target <= nums[right] {
                        left = middle + 1
                    } else {
                        right = middle - 1
                    }
                }
            }
            
            return nums[left] == target ? left : -1
        }
    }
    

Log in to reply
 

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