二维数组中的查找

https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

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

思路

1.关键在于起点的选取,二维数组的右上或者左下,如果从右上开始,则只会向左或者向下,如果从左下开始,则只会向右或者向上。
2.刚开始思考时选择起点有误,总想着从左上开始。当前值小于目标值,向右走不了就往下走;当前值大于目标值,向左走不了就往上走。

代码(通过)

public class Solution {
    public static boolean Find(int target, int[][] array) {
         if (array.length == 0 || array[0].length == 0) {
            return false;
        }
        int i = 0, j = array[0].length-1;
        while (true) {
            if (array[i][j]==target){
                return true;
            }else if(array[i][j]>target&&j>0){
                j--;
            }else if(array[i][j]

代码(部分用例无法通过)

public static boolean Find(int target, int[][] array) {
        if(array.length==0||array[0].length==0){
            return false;
        }
        int i = 0, j = 0;
        while (true) {
            if (array[i][j] == target) {
                return true;
            } else if (array[i][j] < target) {
                if (j < array[i].length - 1 && array[i][j + 1] <= target) {
                    j++;
                } else if (i < array.length - 1 && array[i + 1][j] <= target) {
                    i++;
                } else {
                    return false;
                }
            } else {
                if (j >0 && array[i][j - 1] <= target) {
                    j--;
                } else if (i>0 && array[i-1][j] <= target) {
                    i--;
                } else {
                    return false;
                }
            }
        }
    }

你可能感兴趣的:(二维数组中的查找)