• 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

  • 相关阅读:
    Win7+Ubuntu11.10(EasyBCD硬盘安装)
    hdu 3661 Assignments
    hdu 1128 Self Numbers
    CF 152 B. Chilly Willy
    hdu 1754 I Hate It
    A survey of wireless network simulation and/or emulation software for use in higher education
    How to Fix Packet Loss: Causes, Simple Solutions & Top Tools
    getchar函数
    C++“左值”和“右值”
    stdio.h中的stdio
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12354477.html
Copyright © 2020-2023  润新知