剑指offer–二维数组中的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
选取右上角元素,target 大于array[i][j], 则剔除整行;
target 小于array[i][j],则删除整列;
public boolean Find(int target, int [][] array)
注意:
1.我们在选取第一个数来与target比较大小时,一定要选取数组中最靠边的数也就是每行每列最后一个数。因为这样在比较大小时,在选取第二个数比较时不会出现冲突。
2.在比较前可以判断数组是否为空,查找的这个数是否在数组中。
主程序代码Solution:
public class Solution {
public boolean Find(int target, int [][] array) {
int row = array.length;
//cannot be col = array[1].length, in case array is empty
int col = array[0].length;
if (row <= 0 || col <= 0) {
return false;
}
if (target < array[0][0] || target > array[row-1][col-1]) {
return false;
}
int i = 0;
int j = col-1;
while (i < row && j > 0) {
if (target > array[i][j]) {
i++;
}
if (target < array [i][j]) {
j--;
}
if (target == array[i][j]) {
return true;
}
}
return false;
}
}
测试代码:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//test case1: {{1,2,8,9},{4,7,10,13}} find 7
// test case2: {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}} find 5
int array[][] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
// test case3: {{}} find 16
int array1 [][] = {{}};
Solution solution = new Solution();
boolean temp = solution.Find(5, array);
System.out.println(temp);
boolean temp 1= solution.Find(16, array1);
System.out.println(temp1);
}
}