题目链接:
链接
题目描述:
思路:
- 可以发现,如果把每一行拼起来,就是一个递增的数组,可以在这个递增的数组上使用二分法找到target
- 如果拼起来的某个元素索引是i,那它在二维矩阵里面的索引是【i/列数,i%列数】
- 所以在代码里不需要真正执行 拼起来 这个操作,知道i就行
- i是用二分法得到的索引,可以知道假设拼起来的数组索引范围是0~行数*列数-1
实现代码:
class Solution {public boolean searchMatrix(int[][] matrix, int target) {int m = matrix.length, n = matrix[0].length;int low = 0 , high = m*n -1;while(low <= high){int mid = (high - low) / 2 + low;int x = matrix[mid/n][mid%n];if(x < target){low = mid +1;}else if(x > target){high = mid -1;}else{return true;}}return false;}
}