
Sponsored
Sponsored
This approach begins searching from the top-right corner of the matrix. If the current element is equal to the target, return true. If the current element is greater than the target, move left. If the current element is less than the target, move down. This method effectively narrows down the search space, taking advantage of the sorted property of the matrix.
Time Complexity: O(m + n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1), as no extra space is used.
1public class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 int row = 0, col = matrix[0].length - 1;
4 while (row < matrix.length && col >= 0) {
5 if (matrix[row][col] == target) {
6 return true;
7 } else if (matrix[row][col] > target) {
8 col--;
9 } else {
10 row++;
11 }
12 }
13 return false;
14 }
15}In Java, the solution follows the same logic by initializing pointers at the top-right and changing them according to the condition. The method iteratively moves through the matrix to locate the target.
This approach uses binary search on each row of the matrix. Since each row is sorted, binary search can efficiently determine if the target exists within the row. If found in any row, the function returns true.
Time Complexity: O(m * log(n)), where m is the number of rows and n is the number of columns.
Space Complexity: O(1).
1#
The C code uses a helper function `binarySearch` to search within a row. It iterates through each row of the matrix and applies binary search. If the target is found in any row, it returns true; otherwise, it iterates through all rows and returns false afterward.