第9天 二维数组中查找指定数字

来源:互联网 发布:iis7端口设置 编辑:程序博客网 时间:2024/05/02 04:46



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

1   2   8   9

2   4   9   12

4   7   10  13

6   8   11  15



/** * 面试题3:二维数组中的查找 *  * 排除不满足的数据 * 习惯性的从左上角或者右下角开始排查 * 相反 *  *横向、纵向搞反了 * **** 数组或者字符串,如果要插入尽量后向前插入,这样可以减少向后移动次数 */public class FindInPartiallySortedMatrix {public boolean search(int[][] data, int indexValue) {if (data == null || data.length <= 0) {return false;}int rowLength = data.length;int j = 0;while (j < rowLength) { // 从左往右,没找到就返回int length = data[j].length;if (data[length-1][j] > indexValue) {break;} else if (data[length-1][j] < indexValue) {j++;} else {return true;}}if (j == rowLength) {return false;}int i = data[j].length - 1;while (i >= 0) { // 从下往上if (data[i][j] > indexValue) {i--;} else if (data[i][j] < indexValue) {return false;} else {return true;}}return false;}public static void main(String[] args) {int[][] arr = {{1, 2, 8, 9},{2, 4, 9, 12},{4, 7, 10, 13},{6, 8, 11, 15}};FindInPartiallySortedMatrix sorted = new FindInPartiallySortedMatrix();boolean value = true;value = value && sorted.search(arr, 6);value = value && sorted.search(arr, 8);value = value && sorted.search(arr, 11);value = value && sorted.search(arr, 15);value = value && !sorted.search(arr, 16);value = value && sorted.search(arr, 4);value = value && sorted.search(arr, 7);value = value && sorted.search(arr, 10);value = value && sorted.search(arr, 13);value = value && !sorted.search(arr, 14);value = value && sorted.search(arr, 2);value = value && sorted.search(arr, 4);value = value && sorted.search(arr, 9);value = value && sorted.search(arr, 12);value = value && !sorted.search(arr, 19);value = value && sorted.search(arr, 1);value = value && sorted.search(arr, 2);value = value && sorted.search(arr, 8);value = value && sorted.search(arr, 9);value = value && !sorted.search(arr, -1);System.out.println( value + " - " +  System.currentTimeMillis() );}}

《剑指offer》面试题3


0 0