The first title to prove safety offer two-dimensional array to find

Title Description

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

solution

In addition to brute force than read line by line, the method used here is to start from the bottom left corner

For several lower left corner, diminishing upwards, to the right is incremented. So you can easily traverse

For the target, if the number is greater than the current, then go to the right hand, is less than, the pointer to go up. If equal, return true.

Note that this particular boundary conditions, it is determined that 0, target larger than the maximum, it is smaller than the smallest.

public class Solution {
    public boolean Find(int target,int[][] array){
        int len =array.length;
        //array.length == 0                         判断{}
        //(array.length ==1)&&(array[0].length ==0) 判断{{}}
        if(array.length == 0 ||((array.length ==1)&&(array[0].length ==0)))
            return false;
        //target比最大的大,比最小的小,那么直接false
        if(target <array[0][0] ||target >array[len-1][len-1]){
            return false;
        }
        int i=len-1,j =0;
        while(i >= 0 && j <=len-1){
            if(array[i][j] ==target){
                return true;
            }else if(target >array[i][j]){
                j++;
            }else if(target <array[i][j]){
                i--;
            }
        }
        //if(array[i][j] ==target)
        //return true;
        //else
        //return false;
        return false;
    }
}

By then the brush title

Guess you like

Origin blog.csdn.net/blood_ing_/article/details/93297948