Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
思路:此题还是比較简单的。主要是用两个二分法,才对第一列使用,再对特定的行使用。
详细代码例如以下:
public class Solution { public boolean searchMatrix(int[][] m, int target) { //两个二分搜索 //先搜索第一列,找到确定的行,然后再搜索行 int i = 0; int j = m.length-1; int mid = 0; //搜寻第一列 while(i <= j){ mid = (i + j)/2; if(m[mid][0] == target){ return true; }else if(m[mid][0] < target){ i = mid + 1; }else{ j = mid - 1; } } if(m[mid][0] > target){ if(mid == 0){ return false; } mid--;//mid-1 } //搜寻mid行 i = 0; j = m[0].length -1; int k = mid; //搜寻到了返回true while(i <= j){ mid = (i + j)/2; if(m[k][mid] == target){ return true; }else if(m[k][mid] < target){ i = mid + 1; }else{ j = mid - 1; } } //没有搜寻到,返回false return false; } }
时间: 2024-10-24 12:26:21