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
相关推荐
lyh1344几秒前
【Fiddler抓取手机数据包】
数据结构
int型码农1 小时前
数据结构第八章(二)-交换排序
c语言·数据结构·算法·排序算法
YKPG1 小时前
C++学习-入门到精通【14】标准库算法
c++·学习·算法
CoovallyAIHub1 小时前
AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别
深度学习·算法·计算机视觉
码农之王2 小时前
记录一次,利用AI DeepSeek,解决工作中算法和无限级树模型问题
后端·算法
落羽的落羽4 小时前
【C++】二叉搜索树
开发语言·数据结构·c++·学习
编程绿豆侠4 小时前
力扣HOT100之二分查找: 34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
Shan12054 小时前
找到每一个单词+模拟的思路和算法
数据结构·算法
纳于大麓5 小时前
数据结构-栈
数据结构
国家不保护废物5 小时前
微信红包算法深度解析:从产品思维到代码实现
javascript·算法·面试