iOS Interview - Leetcode 704. Binary Search

May 07, 20241 min read#swift, #interview, #leetcode

Leetcode: 704. Binary Search

  • Primary idea: Binary search, adjust left and right pointers to narrow down the search space by comparing the middle value with the target.
  • Time Complexity: O(logn)
  • Space Complexity: O(1)
func search(_ nums: [Int], _ target: Int) -> Int {
    var left = 0
    var right = nums.count - 1

    while left <= right {
        var mid = (left+right) / 2
        if nums[mid] == target {
            return mid
        } else if nums[mid] > target {
            right = mid - 1
        } else {
            left = mid + 1
        }
    }

    return -1
}

print(search([-1,0,3,5,9,12], 9)) // 4
print(search([-1,0,3,5,9,12], -1)) // 0
print(search([-1,0,3,5,9,12], 12)) // 5
print(search([-1,0,3,5,9,12], 2)) // -1
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024