1- 思路
二分
2- 实现
⭐74. 搜索二维矩阵——题解思路
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int[] m:matrix){
if(binarySearch(m,target)){
return true;
}
}
return false;
}
public boolean binarySearch(int[] nums,int target){
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]<target){
left = mid +1 ;
}else if (nums[mid] > target){
right = mid-1;
}else{
return true;
}
}
return false;
}
}
3- ACM 实现
public class binarySearch {
public static boolean isHave(int[][] nums ,int target){
for(int[] n:nums){
if(binarySearch(n,target)){
return true;
}
}
return false;
}
public static boolean binarySearch(int[] nums,int target){
int left = 0;
int right = nums.length;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]<target){
left = mid+1;
}else if(nums[mid] > target){
right = mid-1;
}else{
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
input = input.substring(2,input.length()-2);
String[] parts = input.split("],\\[");
String[] row = parts[0].split(",");
int[][] nums = new int[parts.length][row.length];
for(int i = 0 ; i < nums.length ;i++){
String[] r = parts[i].split(",");
for(int j = 0 ; j < r.length;j++){
nums[i][j] = Integer.parseInt(r[j]);
}
}
System.out.println("输入 target");
int t = sc.nextInt();
System.out.println("结果是"+isHave(nums,t));
}
}