牛客--二维数组查找

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


/**
 * @author :Dennis
 * @date :Created in 4/3/2020 21:10
 * @description:
 * @modified By:
 * @version:
 */
public class Solution {
    /**
     * Plan A
     * find column,then,find target by binary search
     *
     * @param target
     * @param array
     * @return
     */
    public static boolean FindPlanA(int target, int[][] array) {
        if (array.length == 0)
            return false;
        for (int i = 0; i < array.length; i++) {
            if (array[i].length == 0)
                return false;
            if (array[i][0] > target || array[i][array[i].length - 1] < target)
                continue;
            //binary search
            int low, mid, high;
            low = 0;
            high = array[i].length - 1;
            while (low <= high) {
                mid = low + (high - low) / 2;
                if (array[i][mid] == target)
                    return true;
                else if (array[i][mid] > target) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            }
        }
        return false;
    }

    /**
     * Plan B
     * find from the bottom left corner,
     * if array[i][j]>target, go up
     * if array[i][j]
    public static boolean FindPlanB(int target, int[][] array) {
        if (array.length == 0)
            return false;
        int i = 0;
        int j = array[0].length - 1;
        while (i < array.length && j >= 0) {
            if (array[i][j] == target)
                return true;
            else if (array[i][j] > target) {
                j--;
            } else {
                i++;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] array = new int[4][4];
        array[0] = new int[]{0, 1, 2, 3};
        array[1] = new int[]{4, 5, 6, 7};
        array[2] = new int[]{8, 9, 10, 11};
        array[3] = new int[]{12, 13, 14, 15};
        boolean stat = FindPlanB(0, array);
        System.out.println("plan a:" + stat);
        stat = FindPlanB(0, array);
        System.out.println("plan b:" + stat);
    }
}

题目地址:https://www.nowcoder.com/questionTerminal/abc3fe2ce8e146608e868a70efebf62e?orderByHotValue=1&questionTypes=000100&page=1&onlyReference=false

你可能感兴趣的:(算法)