Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Write an efficient algorithm that searches for a value target
in an m x n
integer matrix matrix
. This matrix has the following properties:
Example 1:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
Example 2:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false
Constraints:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
-109 <= target <= 109
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length < 1 || matrix[0].length <1) {
return false;
}
int col = matrix[0].length-1;
int row = 0;
while(col >= 0 && row <= matrix.length-1) {
if(target == matrix[row][col]) {
return true;
} else if(target < matrix[row][col]) {
col--;
} else if(target > matrix[row][col]) {
row++;
}
}
return false;
}
}
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = m ? matrix[0].size() : 0, r = 0, c = n - 1;
while (r < m && c >= 0) {
if (matrix[r][c] == target) {
return true;
}
matrix[r][c] > target ? c-- : r++;
}
return false;
}
};
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int)-> bool:
if not len(matrix) or not len(matrix[0]):
# Quick response for empty matrix
return False
h, w = len(matrix), len(matrix[0])
for row in matrix:
# range check
if row[0] <= target <= row[-1]:
# launch binary search on current possible row
left, right = 0, w-1
while left <= right:
mid = left + (right - left) // 2
mid_value = row[mid]
if target > mid_value:
left = mid+1
elif target < mid_value:
right = mid-1
else:
return True
return False
In our experience, we suggest you solve this Search a 2D Matrix II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Search a 2D Matrix II LeetCode Solution
I hope this Search a 2D Matrix II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>