版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/86217394
题目及测试
package pid240;
/* 搜索二维矩阵 II
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
*/
public class main {
public static void main(String[] args) {
int[][] testTable = {{1, 4, 7, 11, 15},{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},{10, 13, 14, 17, 24},{18, 21, 23, 26, 30}};
int[] testTable2=new int[]{5,20};
for(int i=0;i<testTable2.length;i++){
test(testTable,testTable2[i]);
}
}
private static void test(int[][] ito,int ito2) {
Solution solution = new Solution();
long begin = System.currentTimeMillis();
System.out.println("ito= ");
for(int i=0;i<ito.length;i++){
for(int j=0;j<ito[i].length;j++){
System.out.print(ito[i][j]+" ");
}
System.out.println();
}
System.out.println();
System.out.println("ito2= "+ito2);
boolean rtn;
rtn=solution.searchMatrix(ito,ito2);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn="+rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功,13ms,很快)
从矩阵的正对角线的两端,他们的两个方向都是都变大或变小,从反对角线的两端,方向是一个变大,一个变小,就可以根据大小,向相应的方向跑过去,直到遇到或者超出矩阵的边界
首先判断(rows-1,0)处的元素,记为x,如果给定的target>x,则延行方向向右寻找,否则延列方向向上寻找。
package pid240;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows=matrix.length;
if(rows==0){
return false;
}
int cols=matrix[0].length;
if(cols==0){
return false;
}
int nowRow=rows-1;
int nowCol=0;
while(nowRow>=0&&nowCol<cols){
int now=matrix[nowRow][nowCol];
if(now==target){
return true;
}
if(now>target){
nowRow--;
continue;
}
else{
nowCol++;
continue;
}
}
return false;
}
}