LeetCode 704 LintCode 14 – Python 3 (Week 09 – 08)

Basic binary search. Time complexity is O(log n). Space complexity is O(1).

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        start = 0
        end = len(nums) - 1
        
        while start + 1 < end:
            mid = int (start + (end - start) / 2)
            if nums[mid] == target:
                end = mid 
            if nums[mid] < target:
                start = mid
            if nums[mid] > target:
                end = mid
        
        if nums[start] == target:
            return start
        if nums[end] == target:
            return end
        
        return -1
         

Leave a comment

Design a site like this with WordPress.com
Get started