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
相关推荐
有一个好名字7 分钟前
力扣:多数元素
算法·leetcode·职场和发展
Koma-forever11 分钟前
List<T>中每次取固定长度的数据
数据结构·list
pystraf20 分钟前
P2572 [SCOI2010] 序列操作 Solution
数据结构·算法·线段树·洛谷
吗喽对你问好31 分钟前
华为5.7机考-最小代价相遇的路径规划Java题解
算法·华为
Trent198537 分钟前
影楼精修-牙齿美型修复算法解析
算法
小王努力学编程2 小时前
高并发内存池(二):项目的整体框架以及Thread_Cache的结构设计
开发语言·c++·学习·算法
补三补四2 小时前
遗传算法(GA)
人工智能·算法·机器学习·启发式算法
dot to one3 小时前
C++ 渗透 数据结构中的二叉搜索树
数据结构·c++·算法·visual studio
长安城没有风3 小时前
数据结构 集合类与复杂度
java·数据结构
好易学·数据结构4 小时前
可视化图解算法36: 序列化二叉树-I(二叉树序列化与反序列化)
数据结构·算法·leetcode·二叉树·力扣·序列化·牛客