【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));
    }
}

相关推荐
未来之窗软件服务5 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
豐儀麟阁贵5 小时前
基本数据类型
java·算法
乐迪信息7 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs8 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛8 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光8 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
StarPrayers.10 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫10 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
2351610 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
weixin_3077791311 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json