题目描述
有一个NxM的整数矩阵,矩阵的行和列都是从小到大有序的。请设计一个高效的查找算法,查找矩阵中元素x的位置。
给定一个int有序矩阵mat,同时给定矩阵的大小n和m以及需要查找的元素x,请返回一个二元数组,代表该元素的行号和列号(均从零开始)。保证元素互异。
测试样例:
[[1,2,3],[4,5,6]],2,3,6
返回:[1,2]
思路:首先选取数组中右上角的数字。如果改数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,剔除这个数字所在的列;如果改数字小于要查找的数字,则剔除这个数字所在的行。也就是说如果要查找的数字不在数组的右上角,则每一次都在数组的查找范围内剔除一行或者一列,这样每一步都可以缩小查找范围,直到找到要查找的数字,或者查找范围为空。
package niuke;
/**
* 从右上角开始,每次将搜索值与右上角的值比较,如果大于右上角的值,则直接去除1行,
* 否则,则去掉1列。算法复杂度O(n),
* 最坏情况需要2n步,即从右上角开始查找,而要查找的目标值在左下角的时候。
* @author Administrator
* 2017/05/03
*/
public class Finder {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
if(mat == null || n==0 || m==0)
return null;
// boolean flag = false;
int[] ret=new int[2];
int row = 0,column = m-1;
while(row < n && column>=0){
if(mat[row][column]==x){
//flag = true;
ret[0]=row;
ret[1]=column;
return ret;
}
else if(mat[row][column]>x)
--column;
else
++ row;
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] mat= {{1,2,8,9},
{2,4,9,12},
{4,7,10,13},
{6,8,11,15}};
//int[] a = new int[]{1,2,4};
Finder fi =new Finder();
int[] ret=fi.findElement(mat, 4, 4,7 );
System.out.println(Arrays.toString(ret));
}
}