二维数组中查找
描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列也都是按照从上到下递增的顺序排序。完成一个函数,输入一个二维数组和一个整数,判断该数组中是否含有该整数。
方法
最开始的想法肯定就是暴力搜索了,双重for循环,但是这样就和题目中给定的递增的条件没什么关系了,显然不是题目的本意。于是,采取另一种办法,每次搜索从是从二维数组的右上角开始。若是大于目标数,删掉该行;同理,如果小于目标数,删掉该列。
重点:
- 起初要判断数组是否为空[Line3-4]
- 实时判断当前所处的位置是否合理(当你使用不合法的索引访问数组时会报数组越界这种错误,数组arr的合法错误范围是[0, arr.length-1];当你访问这之外的索引时会报这个错。这种错误很像字符串索引越界。)[Line 8-9]
代码
public class Solution {
public static boolean findInPartiallySortedMatrix(int[][] data,int target){
if(data==null ||data.length==0 || data[0].length==0)
return false;
int rowMax = data.length-1,colMax = data[0].length-1;
int rowCur = data.length-1,colCur = 0;
while(true){
if(rowCur<0 | rowCur>rowMax | colCur<0 | colCur>colMax)
return false;
if(data[rowCur][colCur]==target)
return true;
else if(data[rowCur][colCur]>target)
rowCur--;
else
colCur++;
}
}
public static void main(String[] args){
int[][] data = {{1,2,8,9},
{2,4,9,12},
{4,7,10,13},
{6,8,11,15}};
System.out.println(findInPartiallySortedMatrix(data, 10));
System.out.println(findInPartiallySortedMatrix(data, 5));
}
}