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
相关推荐
小羊没烦恼!几秒前
系统内部模块(子系统)之间的耦合以及模块(子系统)划分
java·开发语言·前端·数据库·算法·c#
Nebula_g7 分钟前
JavaSE拓展:Arrays和Collections工具类
java·开发语言·算法·排序算法·工具类·javase·技术栈
菜鸟~noob23313 分钟前
【电子战】 第22篇:误差椭圆与置信区间【含matlab代码】
开发语言·算法·matlab
weixin_3077791325 分钟前
C++代码实现MATLAB中的normalize函数功能
开发语言·c++·算法·matlab
不会就选b38 分钟前
算法日常・每日刷题--<动态规划>11
算法
(Charon)40 分钟前
【C++面试】手写String类:同时实现拷贝构造与移动构造
c++·算法
迷途之人不知返1 小时前
算法系列6:模拟
算法
旺仔仔仔1 小时前
# 机器人项目实战(1):选相机、试深度,再到手眼标定
算法
CoderYanger1 小时前
A.每日一题:1614. 括号的最大嵌套深度
java·程序人生·算法·leetcode·面试·学习方法
yuki蜜语1 小时前
别只会调包跑模型!一文讲透大模型训练底层的“递推、递归、三明治”三重逻辑
算法