牛客网的剑指offer题集

  • 数组
  • 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
//简单遍历
public class Solution {
    public boolean Find(int target, int [][] array) {
        for(int i=0;i<array.length;++i){
            for(int j=0;j<array[0].length;++j){
                if(array[i][j]==target){
                    return true;
                }
            }
        }
        return false;
    }
}
//分析,从左到右递增,从上到下递增可以从左下角开始,行-1变小,列+1变大,需要考虑很多边界情况。

public class Solution {
    public boolean Find(int target, int [][] array) {
        int width = array[0].length;
        int height = array.length;
        if(width==0||height==0)
            return false;
        int i = height - 1;
        int j = 0;
        while (true) {
            if (array[i][j] == target)
                return true;
            else if (array[i][j] < target) {
                if (j < width - 1)
                    j++;
                else {
                    return false;
                }
            } else if (array[i][j] > target) {
                if (i > 0)
                    i--;
                else {
                    return false;
                }
            }
            if (i == 0 && j == width - 1) {
                return false;
            }
        }
    }
}
//最后膜拜一下巨佬简洁明了的代码
public class Solution {
    public boolean Find(int [][] array,int target) {
        int row=0;
        int col=array[0].length-1;
        while(row<=array.length-1&&col>=0){
            if(target==array[row][col])
                return true;
            else if(target>array[row][col])
                row++;
            else
                col--;
        }
        //通过越界来说明超出,厉害了。
        return false;
 
    }
}

猜你喜欢

转载自www.cnblogs.com/neoLin/p/11582008.html