题目:
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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
题解:
从右上找。
C++版:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = 0, col = matrix[0].size() - 1;
while(row < matrix.size() && col >= 0) {
if(matrix[row][col] == target)
return true;
else if(matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
};
Java版:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0, col = matrix[0].length - 1;
while(row < matrix.length && col >= 0) {
if(matrix[row][col] == target)
return true;
else if(matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
}
Python版:
class Solution:
# @param {integer[][]} matrix
# @param {integer} target
# @return {boolean}
def searchMatrix(self, matrix, target):
row, col = 0, len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False