-
BingoPython解法一:
class Solution: # @param {integer[][]} matrix # @param {integer} target # @return {boolean} def searchMatrix(self, matrix, target): y = len(matrix[0]) - 1 for x in range(len(matrix)): while y and matrix[x][y] > target: y -= 1 if matrix[x][y] == target: return True return False
-
BingoPython解法二:
class Solution: # @param {integer[][]} matrix # @param {integer} target # @return {boolean} def searchMatrix(self, matrix, target): y = len(matrix[0]) - 1 def binSearch(nums, low, high): while low <= high: mid = (low + high) / 2 if nums[mid] > target: high = mid - 1 else: low = mid + 1 return high for x in range(len(matrix)): y = binSearch(matrix[x], 0, y) if matrix[x][y] == target: return True return False
-
BingoJava:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { int n=matrix.length, m=matrix[0].length; return helper(matrix,0,n-1,0,m-1,target); } boolean helper(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd, int target ){ if(rowStart>rowEnd||colStart>colEnd){ return false; } int rm=(rowStart+rowEnd)/2, cm=(colStart+colEnd)/2; if(matrix[rm][cm]== target){ return true; } else if(matrix[rm][cm] >target){ return helper(matrix, rowStart, rm-1,colStart, cm-1,target)|| helper(matrix, rm, rowEnd, colStart,cm-1,target) || helper(matrix, rowStart, rm-1,cm, colEnd,target); } else{ return helper(matrix, rm+1, rowEnd, cm+1,colEnd,target)|| helper(matrix, rm+1, rowEnd, colStart,cm,target) || helper(matrix, rowStart, rm,cm+1, colEnd,target); } }
-
BingoC++:
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; if (target < matrix[0][0] || target > matrix.back().back()) return false; int x = matrix.size() - 1, y = 0; while (true) { if (matrix[x][y] > target) --x; else if (matrix[x][y] < target) ++y; else return true; if (x < 0 || y >= matrix[0].size()) break; } return false; } };
-