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;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章