二分查找

算法入门第一题      二分查找

思路:在一个升序的list中,用中间数(mid)来进行匹配,如果target比中间数大,说明target在list右边,left=mid+1,如果target比中间数小,说明target在list左边,right=mid-1

from typing import List


class Solution:
    def search(self, nums: List[int], target: int) -> int:
        # write code here

        if len(nums) == 0:
            return -1
        left = 0
        right = len(nums) - 1

        while left <= right:
            mid = int((left + right) / 2)

            if nums[mid] < target:
                left = mid + 1
            elif nums[mid] > target:
                right = mid - 1
            else:
                return mid
            # elif nums[mid] == target:
            #     return mid
        return -1


list1 = [9]
s = Solution()
print(s.search(list1, 2))

 

posted @ 2023-11-21 17:46  TW-NLP  阅读(13)  评论(0编辑  收藏  举报