[Offer] [4] [find] a two-dimensional array

Title Description

  In a two-dimensional array, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Ideas analysis

  Because of a given group is a two-digit increment from left to right, top to bottom increments, so you can choose one corner (upper or lower left corner) to begin a two-dimensional array of search and filter, for example: from the top right start, if the target number is greater than the upper-right corner of numbers (due to the increment from left to right), indicating that digital're looking for below the first row, then the number of the first row can be ruled out, continue to look this way, they can investigation target figures

Java code

public class Offer004 {
    public static void main(String[] args) {
//      int [][] arr = {{},{}}; 
        int [][] arr = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; 
//      System.out.println(arr.length);
//      System.out.println(arr[0].length);
        System.out.println(Offer004.findInPartiallySortedMatrix(arr, 11));
        System.out.println(Offer004.findInPartiallySortedMatrix(arr, 7));
    }
    public static boolean findInPartiallySortedMatrix(int[][] arr, int target) {
        return Solution1(arr, target);
    }
    
    /**
     * 从右上角开始找,如果目标数字小于右上角数字,j--,大于i++,依次缩小查找的范围
     *              
     * @param arr
     * @param target
     * @return
     */
    public static boolean Solution1(int[][] arr, int target) {
        if(arr==null || arr.length<=0 || arr[0].length<=0 ) {
            throw new IllegalArgumentException("参数非法!");
        }   
        int i=0;
        int j= arr[0].length-1;
        while(i<arr.length && j>=0) {
            if(target<arr[i][j]) {
                j--;
            }else if(target>arr[i][j]){
                i++;
            }else {
                return true;
            }
        }   
        return false;
    }
}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer4-er-wei-shu-zu-zhong-de-cha-zhao.html