leetcode_20:二维数组查找

package divide_and_conquer;

public class leetcode_240 {
	
	/**
	 * 240搜索二维数组
	 *
	 */
	
	public static void main(String[] args) {
		int[][] matrix = {{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}};
		System.out.println(searchMatrix(matrix, 5));
		
	}
	
	/**
	 * 
	 * 思路非常简单,从右上角开始进行查找,如果target大于matrix[i][j]则查找下一行
	 *                                如果target小于matrix[i][j]则查找上一列
	 * 
	 * 
	 */
    public static boolean searchMatrix(int[][] matrix, int target) {
    	
    	if(matrix == null) {
    		return false;
    	}

    	if(matrix.length == 0) {
    		return false;
    	}
    	int rows = matrix.length;
    	int cols = matrix[0].length;
    	
    	int i = 0;
    	int j = cols-1;
    	while(i<rows && j>=0 ) {
    		if(matrix[i][j] == target) {
    			return true;
    		}else if(matrix[i][j] > target) {
    			--j;
    		}else {
    			++i;
    		}
    	}

        return false;
    }

}

你可能感兴趣的:(leetcode)