您的位置:首页 > 其它

二维数组的查找

2015-10-05 16:56 260 查看
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

类似二分查找,我们每次选择一个中心元素a[t1][t2],然后我们可以将这个数组分割成A、B、C、D四块。

AB
CD


target == a[t1][t2]


就是找到了;



target > a[t1][t2]


那A就不要查找了,只要查找B、C、D;



target < a[t1][t2]


那D就不用找了,只要再查找A、B、C;

所以,代码如下:

public class Solution {
public boolean Find(int[][] array, int target) {
int m = array.length;
if (m==0) return false;
int n = array[0].length;
if (n==0) return false;
if(m==1 && n==1) return target==array[0][0];
return FindTarget(array, target, 0, 0, m-1, n-1);
}

private boolean FindTarget(int[][] array, int target,
int x1, int y1, int x2, int y2) {
if(x1==x2 && y1==y2) return target==array[x1][y1];
if (target==array[x1][y1] || target==array[x2][y2]) return true;
if (target<array[x1][y1] || target>array[x2][y2]) return false;
if (x1==x2 && y1+1==y2) return false;
if (y1==y2 && x1+1==x2) return false;
if (x1+1==x2 && y1+1==y2) return(target==array[x1+1][y1]
||target==array[x1][y1+1]);
int t1 = (x1+x2)/2;
int t2 = (y1+y2)/2;
if (array[t1][t2]==target) return true;
else if (target>array[t1][t2]) {
return (FindTarget(array, target, t1, t2, x2, y2)
|| FindTarget(array, target, x1, t2, t1, y2)
|| FindTarget(array, target, t1, y1, x2, t2));
}
else {
return (FindTarget(array, target, x1, y1, t1, t2)
|| FindTarget(array, target, x1, t2, t1, y2)
|| FindTarget(array, target, t1, y1, x2, t2));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: