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
相关推荐
努力学算法的蒟蒻2 分钟前
day49(12.30)——leetcode面试经典150
算法·leetcode·面试
天赐学c语言2 分钟前
12.30 - 合并区间 && C++中class和C语言中struct的区别
c语言·c++·算法·leecode
报错小能手16 分钟前
数据结构 b树(b-)树
数据结构·b树
有一个好名字19 分钟前
力扣-递增的三元子序列
算法·leetcode·职场和发展
陌路2019 分钟前
S31 B树详解
数据结构·b树
Boop_wu21 分钟前
[Java 数据结构] 图(1)
数据结构·算法
无尽的罚坐人生25 分钟前
hot 100 128. 最长连续序列
数据结构·算法·贪心算法
Savior`L28 分钟前
基础算法:模拟、枚举
数据结构·c++·算法
软件算法开发37 分钟前
基于蘑菇繁殖优化的LSTM深度学习网络模型(MRO-LSTM)的一维时间序列预测算法matlab仿真
深度学习·算法·matlab·lstm·时间序列预测·蘑菇繁殖优化·mro-lstm
雪花desu38 分钟前
【Hot100-Java中等】LeetCode 11. 盛最多水的容器:双指针法的直观理解与数学证明
算法·leetcode