目录
- [1- 思路](#1- 思路)
-
- [2- 实现](#2- 实现)
-
- [⭐240. 搜索二维矩阵 II------题解思路](#⭐240. 搜索二维矩阵 II——题解思路)
- [3- ACM 实现](#3- ACM 实现)
1- 思路
二分法
- 针对每行一维数组进行二分,对 target 进行二分
2- 实现
⭐240. 搜索二维矩阵 II------题解思路
java
复制代码
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int [] m:matrix){
if(binarySearch(m,target)>=0){
return true;
}
}
return false;
}
private int binarySearch(int[] nums,int target){
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = (right+left)/2 ;
if(nums[mid]==target){
return mid;
}else if(nums[mid] < target){
left = mid+1;
}else{
right = mid-1;
}
}
return -1;
}
}
3- ACM 实现
java
复制代码
public class searchMatrix {
private static boolean searchM(int[][] matrix,int target){
for (int[] n:matrix){
if(binarySearch(n,target)>=0){
return true;
}
}
return false;
}
private static int binarySearch(int[] nums,int target){
int left = 0;
int right = nums.length;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid] == target){
return mid;
}else if (nums[mid] > target){
right = mid-1;
}else{
left = mid+1;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数组行数m");
int m = sc.nextInt();
System.out.println("输入数组列数n");
int n = sc.nextInt();
int[][] nums = new int[m][n];
for(int i = 0 ;i < m;i++){
for(int j = 0 ; j < n;j++){
nums[i][j] = sc.nextInt();
}
}
System.out.println("输入target");
int target = sc.nextInt();
System.out.println("结果是"+searchM(nums,target));
}
}