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
相关推荐
白白白小纯38 分钟前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
手写码匠1 小时前
华为云Flexus+DeepSeek征文|Dify 构建企业级联网搜索 Agent:查询改写、多源检索与引用溯源实战
人工智能·深度学习·算法·aigc
七夜zippoe1 小时前
DolphinDB 能耗统计分析实战:报表生成、同比环比与定额对比
人工智能·算法·dolphindb·报表生成·能耗统计·定额对比
为啥全要学1 小时前
在大语言模型上使用 PPO 算法
人工智能·算法·语言模型
zander2582 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
汤愈韬2 小时前
模型求解算法
人工智能·算法·机器学习
Keven_112 小时前
算法札记:DP中的滚动数组
算法·滚动数组
luj_17682 小时前
随机性在算法与占卜中的共通原理
c语言·开发语言·c++·经验分享·算法
Chen—LSN3 小时前
C语言——深度理解指针(5)
c语言·数据结构·算法·排序算法
佳児素花痴╮5 小时前
树的基础知识与查找排序算法
数据结构·算法