二分查找-I

求解代码

java 复制代码
public int search (int[] nums, int target) {
        // 左指针:起始下标
        int left = 0;
        // 右指针:结束下标,闭区间 [left, right]
        int right = nums.length - 1;

        while (left <= right) {

            int mid = left + ((right - left) >> 1);
            if (nums[mid] < target) {
                // 目标值在右半区,左指针右移
                left = mid + 1;
            } else if (nums[mid] == target) {
                // 找到目标值,返回对应下标
                return mid;
            } else {
                // 目标值在左半区,右指针左移
                right = mid - 1;
            }
        }
        // 遍历完无目标值,返回-1
        return -1;
    }
相关推荐
All for pursuit.1 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
Tisfy3 小时前
LeetCode 0678.有效的括号字符串:O(n)+O(1)一次遍历
算法·leetcode·字符串·题解·贪心·括号匹配
Navigator_Z16 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木18 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.21 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用1 天前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi0111 天前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode