704二分查找

题目:给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target  ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
链接:https://leetcode-cn.com/problems/binary-search

法一:参考别人写的两种方法

思路:非常基本的一道二分查找题,运用两种方法,一种左闭右闭,一种左闭右开,都可以实现,在一些复杂的问题中这两种方法可能需要改进,但基本框架不变,

from typing import List
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        # 由于nums的长度至少为1,所以无需提前判断
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) >> 1
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            elif nums[mid] < target:
                left = mid + 1
        return -1

from typing import List
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums)
        while left < right:
            mid = (left + right) >> 1
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid
            elif nums[mid] < target:
                left = mid + 1
        return -1
if __name__ == '__main__':
    solution = Solution()
    # result = solution.search(nums = [-1,0,3,5,9,12], target = 2)
    result = solution.search(nums = [2,5], target = 5)
    print(result)
View Code

ttt

 

posted on 2020-02-23 21:38  吃我一枪  阅读(193)  评论(0编辑  收藏  举报

导航