-
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[ [1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15] ]
给定 target = 7,返回 true。
给定 target = 3,返回 false。
-
示例
在数组中寻找是否有数字7 ,数组为:[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
结果返回:true
在数组中寻找是否有数字3 ,数组为:[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
结果返回:true
-
解题
1、暴力解法
public class Solution {
public boolean Find(int target, int [][] array) {
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
if(target == array[i][j])
return true;
}
}
return false;
}
}
2、相对更好的解法,主要是使用数组本身的特性
public class Solution {
public boolean Find(int target, int [][] array) {
int rows = array.length;
if(rows == 0)
return false;
int col = array[0].length;
if(col == 0)
return false;
int row = rows - 1;
int col = 0;
while(row >=0 && col<cols) {
if(array[row][col] < target) {
col++;
} else if(array[row][col] > target) {
row--;
} else {
return true;
}
}
return false;
}
}