Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

240. Search a 2D Matrix II #104

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

Divide & Conque 从右上角开始, 比较target 和 matrix[i][j]的值. 如果小于target, 则该行不可能有此数, 所以i++; 如果大于target, 则该列不可能有此数, 所以j--. 遇到边界则表明该矩阵不含target. public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 && matrix[0].length == 0) return false; int i = 0; int j = matrix[0].length - 1; while(i < matrix.length && j >= 0) { int x = matrix[i][j]; if(x == target) return true; else if(x < target) i++; else j--; } return false; } }

Shawngbk commented 7 years ago

image