欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 【CT】LeetCode手撕—704. 二分查找

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

2024/10/25 20:37:17 来源:https://blog.csdn.net/weixin_44382896/article/details/140126022  浏览:    关键词:【CT】LeetCode手撕—704. 二分查找

目录

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


题目

  • 原题连接:704. 二分查找

1- 思路

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

2- 实现

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

在这里插入图片描述

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 实现

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com