版权声明:个人博客:转载请注明出处 https://blog.csdn.net/weixin_43161811/article/details/82534978
题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到
下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断
数组中是否含有该整数。
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
解题思路
注意观察:这个二维数组中的任意一个数,它左边的数都比它小,下边的数都比它大。因此,我们从右上角开始查找,可以根据target和当前元素的大小的比较不断缩小范围。
复杂度:O(M + N) + O(1)
public class Test1 {
public boolean find(int target, int[][] nums) {
if (nums == null || nums.length == 0 || nums[0].length == 0)
return false;
// 二维数组行数
int rows = nums.length;
// 第0 行的长度
int cols = nums[0].length;
// 从第一行的最后一个数开始(右上角)
int r = 0, c = cols - 1;
while (r <= rows && c >= 0) {
if (target == nums[r][c])
return true;
else if (target > nums[r][c])
r++;//数大了 行数+1
else
c--;//数小了 列数-1
}
return false;
}
//测试
public static void main(String[] args) {
int target = 11;// 目标数字
int[][] nums = new int[][] { // 数组
{ 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 } };
// System.out.println(A.length);// 4,表示数组的行数
// System.out.println(A[0].length);// 2,表示对应行的长度
// System.out.println(A[1].length);// 2
// System.out.println(A[2].length);// 5
if (new Test1().find(target, nums)) {
System.out.println("找到了:" + target);
} else
System.out.println("没有找到:" + target);
}
}