|
| 1 | +--- |
| 2 | +id: search-a-2d-matrix-ii |
| 3 | +title: Search A 2D Matrix ii |
| 4 | +sidebar_label: 0240-Search A 2D Matrix ii |
| 5 | +tags: |
| 6 | + - DP |
| 7 | + - Leet code |
| 8 | +description: "Solution to leetocde 240" |
| 9 | +--- |
| 10 | + |
| 11 | +## Approach |
| 12 | +The approach involves starting from the top-right corner of the matrix and iteratively narrowing down the search based on comparisons with the target. |
| 13 | + |
| 14 | +1. Initialize `m` and `n` to the number of rows and columns in the matrix, respectively. Also, initialize `r` to 0 (the topmost row) and `c` to `n - 1` (the rightmost column). |
| 15 | +2. Enter a while loop that continues as long as the current position is within the matrix (`r < m` and `c >= 0`). |
| 16 | +3. Inside the loop, compare the element at the current position (`r, c`) with the target. |
| 17 | + - If they are equal, it means the target is found, and the function returns `true`. |
| 18 | + - If the element is greater than the target, update `c` to move to the left, narrowing down the search. |
| 19 | + - If the element is less than the target, update `r` to move downwards, narrowing down the search. |
| 20 | +4. The loop continues until the search range is exhausted or the target is found. |
| 21 | +5. If the loop completes without finding the target, the function returns `false`. |
| 22 | + |
| 23 | +## Time Complexity |
| 24 | +The time complexity of this code is `O(m + n)`, where `m` is the number of rows and `n` is the number of columns in the matrix. In each iteration of the while loop, either `r` is incremented or `c` is decremented, leading to a total of at most `m + n` iterations. |
| 25 | + |
| 26 | +## Space Complexity |
| 27 | +The space complexity of this code is `O(1)` because it uses only a constant amount of extra space for variables (`m`, `n`, `r`, `c`). The space usage does not depend on the size of the input matrix. |
| 28 | + |
| 29 | +```cpp |
| 30 | +class Solution { |
| 31 | +public: |
| 32 | + bool searchMatrix(vector<vector<int>>& matrix, int target) { |
| 33 | + |
| 34 | + int m = matrix.size(), n = matrix[0].size(), r = 0, c = n - 1; |
| 35 | + |
| 36 | + while (r < m && c >= 0){ |
| 37 | + |
| 38 | + if (matrix[r][c] == target) |
| 39 | + return true; |
| 40 | + else if(matrix[r][c] > target) |
| 41 | + c--; |
| 42 | + else |
| 43 | + r++; |
| 44 | + } |
| 45 | + |
| 46 | + return false; |
| 47 | + } |
| 48 | +} |
| 49 | +``` |
0 commit comments