Leetcode[0]:⭐ - 704. Binary Search

704. Binary Search

Pointers

문제를 해결하기 위해서는 세 가지 인덱스 변수가 필요하다.

left: 왼쪽 경계를 나타내는 인덱스 변수. Inclusive

right: 오른쪽 경계를 나타내는 인덱스 변수. Inclusive

mid: target과 비교대상이 되는 변수.

    target < mid: go left
    target > mid: go right

Loop

특정한 조건이 만족하는 경우에만 loop 수행 –> while loop을 사용.

Source Code

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