题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
给定 target = 7,返回 true。
给定 target = 3,返回 false。
输入:7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
输出:true
输入:3,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
输出:false
思路:
观察矩阵右上角的数组,该数字是当前所在列的最小值,是当前所在行的最小值,即该数在从行到列数字中的中间值,所以可以用二分查找的思想。
- 从右上角开始,首先选中右上角的数字,如果该数字等于要查找的数字,则查找过程结束。
- 如果当前数字大于target,剔除该数字所在的列,则target只会出现在行上,因为这一列上的数字都会大于target。
- 如果当前数字小于target,则剔除该数字所在的行,去列上找,因为这一行中的数字都会小于target。
public class Solution {
public boolean Find(int target, int [][] array) {
if (array == null || array.length == 0 || array[0].length == 0) return false;
int rows = array.length; //行数
int cols = array[0].length; //列数
//从右上角开始
int row = 0;
int col = cols - 1;
while (row < rows && col >= 0) {
if (array[row][col] == target) {
return true;
} else if (array[row][col] > target) {
col--;//把查询范围剔除该列
}else{
row++;//把查询范围剔除该行
}
}
return false;//矩阵遍历结束都没找到,返回false
}
}
原文地址:https://blog.youkuaiyun.com/YouMing_Li/article/details/114235580