剑指offer题解【二维数组中的查找】-java

剑指offer题解【二维数组中的查找】-java

package test;

public class Solution {

    public static void main(String[] args) {
        int [][] array = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
        int target = 7;
        boolean isExist = Find(array,target);
        System.out.println(isExist);
    }

    public static boolean Find(int [][] array,int target) {
        boolean isExist = false;
        int rows = array.length;
        int columns = array[0].length;
        int row = 0;
        int column  = columns - 1;
        if((array != null) &&(rows > 0) && (columns > 0)) {
            if((array[0][0] > target) | array[rows-1][columns -1] < target) {
                isExist = false;
            } else {
                while( (row < rows) && (column >= 0) ){
                    if(target < array[row][column]) {
                        --column;
                    } else if(target > array[row][column]) {
                        ++ row;
                    } else {
                        isExist = true;
                        break;
                    }
                }
            }
        }
        return isExist;
    }
}

推荐牛客网剑指offer在线测试地址:
http://www.nowcoder.com/ta/coding-interviews?page=1

你可能感兴趣的:(java深入学习,二维数组,java,剑指offer)