编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
法一:暴力搜索
执行用时:13ms,在所有Java提交中击败了12.96%的用户
内存消耗:44.1MB,在所有Java提交中击败了19.69%的用户
法2:从矩阵左下角找
从左下角开始,如果与目标值相等就返回true,如果大了就往上(row--),小了就往右(col++)
执行用时:5ms,在所有Java提交中击败了96.40%的用户
内存消耗:43.7MB,在所有Java提交中击败了81.51%的用户
法3:从矩阵右上角找
从右上角开始,如果与目标值相等就返回true,如果大了就往左(col--),小了就往下(row++)
执行用时:5ms,在所有Java提交中击败了96.40%的用户
内存消耗:43.8MB,在所有Java提交中击败了77.58%的用户
package 数组;
public class 搜索二维矩阵2 {
/*
法一:暴力搜索
执行用时:13ms,在所有Java提交中击败了12.96%的用户
内存消耗:44.1MB,在所有Java提交中击败了19.69%的用户
*/
public boolean searchMatrix(int[][] matrix, int target) {
boolean flag=false;
outer: for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j]==target){
flag=true;
break outer;
}
}
}
return flag;
}
/*
法2:从矩阵左下角找
从左下角开始,如果与目标值相等就返回true,如果大了就往上(row--),小了就往右(col++)
执行用时:5ms,在所有Java提交中击败了96.40%的用户
内存消耗:43.7MB,在所有Java提交中击败了81.51%的用户
*/
public static boolean searchMatrix2(int[][] matrix, int target){
int row=matrix.length-1;
int col=0;
while (row>=0&&col<matrix[0].length){
if (matrix[row][col]>target)
row--;
else if (matrix[row][col]<target)
col++;
else return true;
}
return false;
}
/*
法3:从矩阵右上角找
从右上角开始,如果与目标值相等就返回true,如果大了就往左(col--),小了就往下(row++)
执行用时:5ms,在所有Java提交中击败了96.40%的用户
内存消耗:43.8MB,在所有Java提交中击败了77.58%的用户
*/
public static boolean searchMatrix3(int[][] matrix, int target){
int col=matrix[0].length-1;
int row=0;
while (col>=0&&row<matrix.length){
if (matrix[row][col]>target)
col--;
else if (matrix[row][col]<target)
row++;
else return true;
}
return false;
}
public static void main(String[] args) {
int a[][]={{-1,3}};
System.out.println(searchMatrix3(a,3));
}
}