
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 bool SearchMatrix(int[][] matrix, int target) {
3 int row = 0;
4 int col = matrix[0].Length - 1;
5 while (row < matrix.Length && col >= 0) {
6 if (matrix[row][col] == target) {
7 return true;
8 } else if (matrix[row][col] > target) {
9 col--;
10 } else {
11 row++;
12 }
13 }
14 return false;
15 }
16}The C# approach uses a similar start-at-the-top-right strategy, with appropriate C# syntax to handle the two-dimensional array navigations.
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).
1function
JavaScript leverages its native array functions to accomplish binary search across each row. It encapsulates this logic within a separate function `binarySearch`, affirming structure and intentionality.