4. 二维数组中的查找
题目链接
题目描述
给定一个二维数组,其每一行从左到右递增排序,从上到下也是递增排序。给定一个数,判断这个数是否在该二维数组中。
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
Copy to clipboardErrorCopied
解题思路
要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。
该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。
package 二维数组中的查找;/*
作者 :XiangLin
创建时间 :18/02/2020 11:51
文件 :FindTarget.java
IDE :IntelliJ IDEA
*/
public class FindTarget {
public boolean Find(int tareget,int[][] martix){
if(martix == null || martix.length == 0 || martix[0].length == 0) //判断二维数组是否存在
return false;
int rows = martix.length,cols = martix[0].length; //求出二维数组列和行的长度
int r = 0,c = cols - 1; //初始状态定位到二维数组的右上角
while (r < rows - 1 && c >= 0){
if (tareget == martix[r][c]) //找到目标值的情况
return true;
else if(tareget > martix[r][c]) //目标值比当前大,说明行要增加,往下走
r ++;
else //目标值比当前小,说明列要减小,往左走
c --;
}
return false;
}
public static void main(String[] args) {
FindTarget find = new FindTarget();
int[][] martix = {
{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 target = 0;
boolean x = find.Find(target,martix);
System.out.println(x);
}
}
输出:
false
It is love that will heal you. It’s what heals us all.
爱会治愈你,会治愈我们所有人。
XiangLin
2020年2月18日于重庆城口
好好学习,天天向上,终有所获