publicbooleansearchMatrix(int[][] matrix, int target){ int r = matrix.length; if(r < 1) returnfalse; int c = matrix[0].length; int i = 0, j = c-1; while(i < r && j >= 0){ if(matrix[i][j] == target) returntrue; elseif(matrix[i][j] < target) i++; else j--; } returnfalse; }
python 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: # @param {integer[][]} matrix # @param {integer} target # @return {boolean} defsearchMatrix(self, matrix, target): y = len(matrix[0]) - 1 for x inrange(len(matrix)): while y and matrix[x][y] > target: y -= 1 if matrix[x][y] == target: returnTrue returnFalse
publicclassSolution{ publicbooleansearchMatrix(int[][] matrix, int target){ int r = matrix.length; if(r < 1) returnfalse; int c = matrix[0].length; return helpFunc(0,0,r-1,c-1,matrix,target); } //divide the matrix into 4 parts and then recursive call //start point and end point private Boolean helpFunc(int sx, int sy, int ex, int ey, int[][]m, int t){ if(t < m[sx][sy] || t > m[ex][ey]) returnfalse; if(sx < ex || sy < ey){ //middle point int mx = (ex-sx)/2+sx; int my = (ey-sy)/2+sy; boolean ret = false; if(my < ey) ret = ret || helpFunc(sx,my+1,mx,ey,m,t); if(mx < ex) ret = ret || helpFunc(mx+1,sy,ex,my,m,t); if(m[mx][my] > t) return helpFunc(sx,sy,mx,my,m,t)||ret; elseif(m[mx][my]<t){ if(mx< ex && my < ey) return helpFunc(mx+1,my+1,ex,ey,m,t)||ret; else return ret; }else returntrue; }else return m[sx][sy] == t; } }