编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
JAVA(遍历数组):
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//int m=matrix.length,n=matrix[0].length;
for(int[] rows:matrix){
for(int col:rows){
if(col==target){
return true;
}
}
}
return false;
}
}
JAVA(二分查找):
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int[] rows:matrix){
int index=search(rows,target);
if (index>=0){
return true;
}
}
return false;
}
//二分查找
public int search(int[] nums, int target) {
int low=0,high=nums.length-1;
while(low<=high){
int mid=(high-low)/2+low;
int num=nums[mid];
if(num==target){
return mid;
}else if(num>target){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
}