二维数组中的查找

来源:互联网 发布:西瓜影音mac版 编辑:程序博客网 时间:2024/06/07 15:55

题目

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整

解题

方法一:暴力
时间复杂度:O(NM)

public class Solution {    public boolean Find(int [][] array,int target) {        if(array == null || array.length == 0 || array[0].length == 0){            return false;        }        int row = array.length;        int col = array[0].length;        for(int i=0;i<row;i++){            for(int j=0;j<col;j++){                if(array[i][j] == target){                    return true;                }            }        }        return false;    }}

方法二:
原始矩阵已经是有序的,利用这个信息每次排除一行或者一列
时间复杂度:O(N+M)

public class Solution {    public boolean Find(int [][] array,int target) {        if(array == null || array.length == 0 || array[0].length == 0){            return false;        }        int row = array.length;        int col = array[0].length;        int i=0; // 行        int j = col - 1; // 列  从右上开始比较        while(i<row && j>= 0){            while(i<row && j>=0){                if(array[i][j] == target){ // 找到                    return true;                }else if(array[i][j] >target){// i j 位置元素比较大,应该向小的方向走                    j = j - 1;                }else{                    i = i + 1;                }            }        }        return false;    }}
0 0