接外包,有相关需求的可以联系我: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))


👇 Share | 分享 👇


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

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


要不聊聊?

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

*

*



微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码