题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
要求:时间复杂度 O(n),空间复杂度 O(1)。
解题思路
该二维数组中的一个数,大于它的数一定在其右边,小于它的数一定在其上边。因此,从左下角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。
代码:
/**
* Created by Moody丶Yang
* Date:2018/4/12
*/
public class Solution4 {
// public static void main(String[] args) {
// int[][] 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}};
// System.out.println(findNum(5, matrix));
// System.out.println(findNum(20, matrix));
// }
public static boolean findNum(int target, int[][] array) {
int rows = array.length;
int cols = array[0].length;
int i = rows - 1, j = 0;
while (i >= 0 && j < cols) {
if (target < array[i][j])
i--;
else if (target > array[i][j])
j++;
else
return true;
}
return false;
}
}