01.二维数组的查找

题目

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

暴力法

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(array[i][j] == target){
                    return true;
                }
            }
        }
        return false;
    }
}

从右上找

public class Solution {
    public boolean Find(int target, int [][] array) {
        int lines = array.length;
        int cols = array[0].length;
            
        int x = 0;
        int y = cols - 1;
        
        while(y>=0 && x<lines){
            if(array[x][y] == target){
                return true;
            }
            if(array[x][y] > target) {
                y--;
            }else{
                x++;
            }
        }
        return false;
    }
}
发布了12 篇原创文章 · 获赞 0 · 访问量 89

猜你喜欢

转载自blog.csdn.net/charlotte_tsui/article/details/105256772