剑指offer第一题:二维数组中的查找
第一节:闲言少叙。
(1)源码
public class Solution {
public static boolean Find(int target, int[][] array) {
int row = array.length;
int col = array[0].length;
if (col == 0 || target < array[0][0] || target > array[row - 1][col - 1]) {
return false;
}
int[] leftTop = new int[] {0, 0};
int[] rightBottom = new int[] {row - 1, col - 1};
while (leftTop[0] <= rightBottom[0] && leftTop[1] <= rightBottom[1]) {
int firstRow = findMiddleIndexInRow(array, target, leftTop[0], leftTop[1], rightBottom[1]);
int firstCol = findMiddleIndexInCol(array, target, leftTop[1], leftTop[0], rightBottom[0]);
rightBottom[0] = firstCol;
rightBottom[1] = firstRow;
if (array[leftTop[0]][rightBottom[1]] == target
|| array[rightBottom[0]][leftTop[1]] == target) {
return true;
}
if (array[leftTop[0]][leftTop[1]] > target
|| array[rightBottom[0]][rightBottom[1]] < target) {
return false;
}
leftTop[0] += 1;
leftTop[1] += 1;
}
return false;
}
public static int findMiddleIndexInRow(int[][] array, int num, int row, int start, int end) {
while (array[row][end] > num && end > start) {
end--;
}
return end;
}
public static int findMiddleIndexInCol(int[][] array, int num, int col, int start, int end) {
while (array[end][col] > num && end > start) {
end--;
}
return end;
}
}
(2)战果
第二节:来龙去脉
**原题描述:**在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
数据样例:
[[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]]
在此数组中查找是否含有数字7,很多聪明的同学就说了,写个循环遍历一下不就知道咯!额,有道理。
如何优雅的干翻此题呢!从题意及数据来看,个人觉得此题就是一个找数据区域的题,一步步压缩数据区域,然后判断数据是否在区域内即可。怎么理解呢?见下图。