剑指 Offer 04. 二维数组中的查找
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:暴力解法
遍历数组
时间复杂度:O(nm),空间复杂度O(1)
方法2:线性查找
从二维数组的右上角开始查找。如果当前元素等于目标值,则返回 true。如果当前元素大于目标值,则移到左边一列。如果当前元素小于目标值,则移到下边一行。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length==0)
return false;
int i=0,j=matrix[i].length-1;
while(i<matrix.length&&j>=0){
if(matrix[i][j]==target){
return true;
}else if(matrix[i][j]<target){
i++;
}else{
j--;
}
}
return false;
}
}
自己的解题思路
我一开始当成二叉树去解,想用队列,但是会超出时间限制,而且队列会重复加入,这个解法不好
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length==0||matrix[0].length==0)
return false;
Node node=new Node(0,0);
Queue<Node> queue=new LinkedList<Node>();
queue.offer(node);
while(!queue.isEmpty()){
node=queue.poll();
if(matrix[node.row][node.col]==target)return true;
if(node.row<matrix.length-1)queue.offer(new Node(node.row+1,node.col));
if(node.col<matrix[0].length-1)queue.offer(new Node(node.row,node.col+1));
}
return false;
}
}
class Node{
int row,col;
Node(int row, int col){
this.row=row;
this.col=col;
}
}