LeetCode - Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following 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] ] Given target = 5, return true. Given target = 20, return false.
观察可知越往右下数越大,加上每一行最后一个数是该行最大值,因此可以根据列值减少搜索的列数。定义 i 为矩阵的行,j 为矩阵的列,初始化 i 为0,j 为最后一列。若目标值大于当前matrix [ i ][ j ] 时,说明此行不可能比目标值大,因此 i+1;若小于,则目标值必然不在此列,因此 j-1;若等于则输出。
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ return false; } int row = matrix.length; int column = matrix[0].length; int r = 0; int c = column - 1; while(r < row && c >= 0){ if(target > matrix[r][c]){ r++; } else if(target < matrix[r][c]){ c--; } else{ return true; } } return false; } }
posted on 2018-10-09 09:36 IncredibleThings 阅读(79) 评论(0) 编辑 收藏 举报