目录
- 题目
- [1- 思路](#1- 思路)
- [2- 实现](#2- 实现)
-
- [⭐704. 二分查找------题解思路](#⭐704. 二分查找——题解思路)
- [3- ACM 实现](#3- ACM 实现)
题目
- 原题连接:704. 二分查找
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));
}
}