【CT】LeetCode手撕—704. 二分查找

目录

  • 题目
  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐704. 二分查找------题解思路](#⭐704. 二分查找——题解思路)
  • [3- ACM 实现](#3- ACM 实现)

题目


1- 思路

  • 模式识别1:查找元素,二分查找

2- 实现

⭐704. 二分查找------题解思路

java 复制代码
class Solution {
    public int search(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        while (l < r) {
            int mid = (l + r + 1) / 2;
            if (nums[mid] <= target) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }

        if (nums[l] != target) {
            return -1;
        } else {
            return l;
        }
    }
}

3- ACM 实现

java 复制代码
public class binarySearch {


    public static int binary(int[] nums,int target){
        int l = 0 ;
        int r = nums.length-1;
        while (l<r){
            int mid = (l+r+1)/2;
            if(nums[mid] == target){
                l = mid;
            }else{
                r = mid-1;
            }
        }

        if(nums[l] == target){
            return l;
        }
        return -1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组长度");
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0 ; i < n ; i ++){
            nums[i] = sc.nextInt();
        }
        System.out.println("输入查找的元素值");
        int t = sc.nextInt();

        System.out.println("下标为"+binary(nums,t));
    }
}

相关推荐
CoovallyAIHub4 小时前
181小时视频丢给GPT-5,准确率只有15%——南大联合NVIDIA等五校发布多模态终身理解数据集
深度学习·算法·计算机视觉
CoovallyAIHub4 小时前
CVPR 2026 | GS-CLIP:3D几何先验+双流视觉融合,零样本工业缺陷检测新SOTA,四大3D工业数据集全面领先!
深度学习·算法·计算机视觉
xlp666hub4 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
有意义7 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub8 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103378 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect8 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研