leetcode704. 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.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9

Output: 4

Explanation: 9 exists in nums and its index is 4

Example 2:

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

Output: -1

Explanation: 2 does not exist in nums so return -1

Constraints:

复制代码
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.

https://leetcode.cn/problems/binary-search/description/

思路:二分查找

「二分查找」是利用数组的有序性,每轮缩窄一半的查找区间(即排除一半元素),直到找到目标值或查找区间为空时返回。

python 复制代码
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        i, j = 0, len(nums) - 1
        while i <= j:
            m = (i + j) // 2
            if nums[m] < target: i = m + 1
            elif nums[m] > target: j = m - 1
            else: return m
        return -1
相关推荐
小O的算法实验室20 分钟前
2026年AST SCI1区TOP,基于速度障碍法的多无人机三维避障策略,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
AlenTech34 分钟前
141. 环形链表 - 力扣(LeetCode)
数据结构·leetcode·链表
U-52184F691 小时前
深入理解“隐式共享”与“写时复制”:从性能魔法到内存深坑
java·数据库·算法
pp起床1 小时前
Part02:基本概念以及基本要素
大数据·人工智能·算法
lzh200409191 小时前
红黑树详解
算法
迈巴赫车主2 小时前
蓝桥杯20560逃离高塔
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
泯仲2 小时前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
dulu~dulu2 小时前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
moonsea02032 小时前
【无标题】
算法
佑白雪乐2 小时前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode