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
相关推荐
平行侠3 分钟前
30MacLaren-Marsaglia算法故事文件
数据结构·算法
灵动小溪10 分钟前
claude code工具PC安装部署
人工智能·算法
Asa121381 小时前
Nature Microbiology|跨微生物界菌株水平传播推断的新算法TRACS
算法
叼烟扛炮1 小时前
C++ 知识点22 函数模板
开发语言·c++·算法·函数模版
Tisfy1 小时前
LeetCode 2553.分割数组中数字的数位:模拟(maybe+翻转)——java也O(1)
java·数学·算法·leetcode·题解·模拟·取模
平行侠1 小时前
33水库抽样 - 从未知大小的流中等概率采样
数据结构·算法
吴声子夜歌2 小时前
Java——Integer与二进制算法
java·算法
Controller-Inversion2 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion2 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
陆水A2 小时前
运输时效预测模型:静态路由时效的计算与验证
大数据·人工智能·算法·spark·数据库开发·etl工程师