/**
*题目:在一个二位数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二位数组和一个整数,
* 判断数组中是否含有该整数
*时间:2015年8月25日09:51:08
*文件:FindInMatrix.java
*作者:cutter_point
*/
package bishi.Offer50.y2015.m08.d25;
public class FindInMatrix
{
/**
* 在一个二维数组中寻找到我们要找的数
* @param matrix 二维数组
* @param rows 行
* @param columns 列
* @param key 我们要寻找的值
* @return
*/
public static boolean Find(int matrix[][], int rows, int columns, int key)
{
boolean found = false; //用来判断是否找到
//首先我们判断数组是否为空
if(matrix == null || rows <= 0 || columns <= 0)
{
System.err.println("数据异常");
return false;
}
//我们知道这是一个递增的数组,我们选这个矩阵的一个对角,比如左下角,作为起始基准进行遍历
int row = rows - 1, col = 0;
//当我们的数比这个数还大的时候,我们就可以判处当前的列,在右边寻找
//当我们的数比这个数小的时候,我们就可以排除当前行,在上面寻找,这样不断逼近我们的值,
while(row > -1 && col < columns)
{
if(matrix[row][col] < key)
{
//比寻找的数大
++col;
}//if
else if(matrix[row][col] > key)
{
//比寻找的数小
--row;
}//else if
else
{
found = true;
break; //找到了之后退出
}//else 相等的时候
}//while在二维数组内寻找
return found;
}
public static void Test(int key)
{
int maxtrix[][] =
{
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 14},
{8, 9, 12, 16}
};
int columns = maxtrix.length;
int rows = maxtrix.clone().length;
boolean find = Find(maxtrix, rows, columns, key);
System.out.println(find);
}
public static void main(String[] args)
{
Test(998);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cutter_point/article/details/47976521