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
相关推荐
weixin_5375904513 分钟前
【任务6.13】计算肇事汽车号码
c++·算法·汽车
从今天开始学习Verilog22 分钟前
FFT算法实现之fft IP核
算法·fpga开发
荼蘼1 小时前
基于 KNN 算法的手写数字识别项目实践
人工智能·算法·机器学习
Yuroo zhou2 小时前
IMU的精度对无人机姿态控制意味着什么?
单片机·嵌入式硬件·算法·无人机·嵌入式实时数据库
jackzhuoa2 小时前
java小白闯关记第一天(两个数相加)
java·算法·蓝桥杯·期末
Codeking__3 小时前
链表算法综合——重排链表
网络·算法·链表
minji...4 小时前
数据结构 堆(4)---TOP-K问题
java·数据结构·算法
AI_Keymaker4 小时前
一句话生成3D世界:腾讯开源混元3D模型
算法
Leon_vibs4 小时前
当 think 遇上 tool:深入解析 Agent 的规划之道
算法
旧时光巷5 小时前
【机器学习-2】 | 决策树算法基础/信息熵
算法·决策树·机器学习·id3算法·信息熵·c4.5算法