本文主要是介绍【Hot100】LeetCode—74. 搜索二维矩阵,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 原题链接: 74. 搜索二维矩阵
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));}
}
这篇关于【Hot100】LeetCode—74. 搜索二维矩阵的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!