Python世界:力扣题704二分查找

Python世界:力扣题704二分查找

任务背景


问题来自力扣题目704:Binary Search,大意如下:

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.

翻译下,需求是:对有序数组进行查找指定数字,若有返回索引,若无返回-1.

思路分析


重温下二分写法,思路很简单,发现值大的下移上界,发现值小的上移下界,直到上下界重合。

要注意的是无target时,mid的偏移问题。

代码实现


python 复制代码
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # range: [low, high)
        low = 0
        high = len(nums)
        while (low < high):
            mid = low + (high - low) // 2
            if nums[mid] < target:
                low = mid + 1
            elif nums[mid] > target:
                high = mid
            else:
                return mid
        # not found
        return -1

   
# test
nums = [-1, 0, 3, 5, 9, 12]
target = 9

# nums = [-1,0,3,5,9,12]
# target = 2

sol = Solution()
res = sol.search(nums, target)
print(res)

测试套件


python 复制代码
# 导入单元测试
import unittest

# 编写测试套
class TestSol(unittest.TestCase):
    # 不在数组中
    def test_special1(self):
        nums = [-1, 0, 3, 5, 9, 12]
        target = 2
        ret = -1
        sol = Solution()
        self.assertEqual(sol.search(nums, target), ret)

    # 下边界
    def test_special2(self):
        nums = [-1, 0, 3, 5, 9, 12]
        target = -1
        ret = 0
        sol = Solution()
        self.assertEqual(sol.search(nums, target), ret)

    # 上边界
    def test_special3(self):
        nums = [-1, 0, 3, 5, 9, 12]
        target = 12
        ret = 5
        sol = Solution()
        self.assertEqual(sol.search(nums, target), ret)

    def test_common1(self):
        nums = [-1, 0, 3, 5, 9, 12]
        target = 5
        ret = 3
        sol = Solution()
        self.assertEqual(sol.search(nums, target), ret)

    def test_common2(self):
        nums = [-1, 0, 3, 5, 9, 12]
        target = 9
        ret = 4
        sol = Solution()
        self.assertEqual(sol.search(nums, target), ret)


# 含测试套版本主调
if __name__ == '__main__':
    print('start!')
    unittest.main() # 启动单元测试
    print('done!')

本文小结


二分核心:索引偏移存乎一心。

可进一步思考若有重复值时,如何找到最小重复索引或最大重复索引。

相关推荐
R-G-B13 分钟前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长14 分钟前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
史迪奇_xxx25 分钟前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_8012522228 分钟前
Java中的反射
java·开发语言
Kiri霧1 小时前
Rust开发环境搭建
开发语言·后端·rust
weixin-a153003083161 小时前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
AI量化投资实验室1 小时前
15年122倍,年化43.58%,回撤才20%,Optuna机器学习多目标调参backtrader,附python代码
人工智能·python·机器学习
倔强青铜三1 小时前
苦练Python第67天:光速读取任意行,linecache模块解锁文件处理新姿势
人工智能·python·面试
小杨同学yx2 小时前
有关maven的一些知识点
java·开发语言
我是华为OD~HR~栗栗呀2 小时前
华为od-21届考研-C++面经
java·c语言·c++·python·华为od·华为·面试