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
相关推荐
he___H4 小时前
数据结构-移位
数据结构
电子_咸鱼5 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫5 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
rit84324995 小时前
基于MATLAB实现基于距离的离群点检测算法
人工智能·算法·matlab
my rainy days7 小时前
C++:友元
开发语言·c++·算法
haoly19897 小时前
数据结构和算法篇-归并排序的两个视角-迭代和递归
数据结构·算法·归并排序
微笑尅乐7 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
小梁努力敲代码7 小时前
java数据结构--List的介绍
java·开发语言·数据结构
im_AMBER8 小时前
算法笔记 05
笔记·算法·哈希算法
夏鹏今天学习了吗8 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展