In this Leetcode Search a 2D Matrix Problem Solution Write an efficient algorithm that searches for a value target in an m x n integer matrix 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.
Problem solution in Python.
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for i in range(len(matrix)):
if target in matrix[i]:
return True
return False
Problem solution in Java.
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix[0].length, start = 0, end = matrix.length*n-1, mid;
while(start<=end) {
mid = (start + end)/2;
if(matrix[mid/n][mid%n]==target) return true;
if(target > matrix[mid/n][mid%n]) start = mid + 1;
else end = mid - 1;
}
return false;
}
Problem solution in C++.
class Solution {
public:
bool searchMatrix(vector<vector>& matrix, int target) {
int row = matrix.size( ), c = matrix[0].size( ) -1, r = 0;
while(r < row && c >= 0){
if(matrix[r][c] == target){
return true;
}
else if(target > matrix[r][c]){
r++;
}
else{
c--;
}
}
return false;
}
};
Problem solution in C.
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
int i;
int j;
i=0;
j=0;
while(i<matrixRowSize)
{
if(target>matrix[i][matrixColSize-1])
{
i++;
}
else
{
while(j<matrixColSize)
{
if(target != matrix[i][j])
{
j++;
}
else
{
return true;
}
}
return false;
}
}
return false;
}
0 Comments