接外包,有相关需求的可以联系我:Telegram | Email

Binary Search

该文章创建(更新)于02/26/2022,请注意文章的时效性!

文章目录[隐藏]

Description

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.

You must write an algorithm with O(log n) runtime complexity.

Code

  • submit code
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums) - 1

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

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

        return -1
  • full code
class Solution:
    def search(self, nums, target):

        left = 0
        right = len(nums) - 1

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

            print(mid)

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

        return -1


nums = [5]
target = 5

S = Solution()
print(S.search(nums,target))

要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2022/02/26/binary-search/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



YouTube | B站

微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码

阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
Just My SocksJMS9272283 【注意手动复制去跳转】
域名 | namesiloemperinter(1美元)
币安 币安