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
相关推荐
2401_8273645643 分钟前
迷宫【BFS+结构体\pair】
算法·宽度优先
于慨2 小时前
计算机考研C语言
c语言·开发语言·数据结构
Bruce Jue2 小时前
算法刷题--贪心算法
算法·贪心算法
慕容魏4 小时前
入门到入土,Java学习 day16(算法1)
java·学习·算法
认真的小羽❅4 小时前
动态规划详解(二):从暴力递归到动态规划的完整优化之路
java·算法·动态规划
Vacant Seat4 小时前
图论-实现Trie(前缀树)
java·开发语言·数据结构·图论
LiDAR点云5 小时前
Matlab中快速查找元素索引号
数据结构·算法·matlab
CYRUS_STUDIO5 小时前
安卓逆向魔改版 Base64 算法还原
android·算法·逆向
JKHaaa5 小时前
数据结构之线性表
数据结构
CYRUS_STUDIO6 小时前
安卓实现魔改版 Base64 算法
android·算法·逆向