二维数组中的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
- 数组从左至右、从上至下都是递增,找到数组中特殊的点即可很方便 处理,即左下角、右上角
- 左下角是该列的最大值,行的最小值,因此在遍历时,大于该值的右移一位,小于该值的上移一位
- 右上角是该列的最小值,行的最大值,因此在遍历时,小于该值的左移一位,大于该值的下移一位
代码
public class Solution {
public static void main(String[] args) {
Solution find = new Solution();
find.test();
}
public boolean Find(int target, int [][] array){
if(array.length == 0){
return false;
}
int rows = array.length;
int cols = array[0].length;
int row = rows - 1;
int col = 0;
while(col<cols && row>=0){
if (target < array[row][col]){
row--;
}
else if (target > array[row][col]){
col++;
}
else{
return true;
}
}
return false;
}
public void test(){
int[][] array = {{1,2,3},{4,5,6},{7,8,9}};
int[][] array_null = {};
int target = 5;
int target_null = 0;
System.out.println(Find(target, array));
System.out.println(Find(target_null, array));
System.out.println(Find(target, array_null));
}
}
时间复杂度:O(m + n)
空间复杂度:O(1)

浙公网安备 33010602011771号