一、思路
总体就是考搜索算法,采用了二分查找进行优化
二、记忆
二分查找的应用思路及写法,在二维举证中对每行应用二分查找即可,不用同时再考虑列
三、代码
3.1直接遍历
public boolean searchMatrix(int[][] matrix,int target){for(int i = 0;i<matrix.length;i++){for(int j = 0;j<matrix[0].length;j++){if (matrix[i][j]==target) return true;}}return false;}
3.2行二分查找
需要注意的是要一直查找到左右指针错位再停止,相等时也要判断
public boolean searchMatrix(int[][] matrix,int target){for(int i = 0;i<matrix.length;i++){int index = search(matrix[i],target);if (index>=0){return true;}}return false;}private int search(int[] nums,int target){int left=0,right = nums.length-1;//注意右指针要长度-1while(left<=right){int mid = (right-left)/2 + left;int num = nums[mid];if (num ==target) return mid;else if (target<num){right = mid-1;}else {left = mid +1;}}return -1;}