본문 바로가기
Problem Solving

[Leetcode] 704. Binary Search

by leeyngdo 2023. 7. 17.

Problem Link: https://leetcode.com/problems/binary-search/

 

Binary Search - LeetCode

Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

leetcode.com

 

Solution 1. Binary Search

Time: $O(\text{log } N)$

Space: $O(1)$ 

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target < nums[0] or target > nums[len(nums) - 1]: return -1
        
        lo = 0; hi = len(nums) - 1
        while lo < hi:
            mid = lo + (hi - lo) // 2
            
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid
            
        return lo if nums[lo] == target else -1