74. Search a 2D Matrix

truongductri01

truongductri01

Posted on October 8, 2023

74. Search a 2D Matrix

Problem: 74. Search a 2D Matrix

Approach

/**
Definitely binary search

2 steps:
- search for which row the target should fall into 
- then search within that row for the target 


How to search for which row 
hasRow = false;
int rowIdx = -1;
leftRow and rightRow

while (leftRow <= rightRow) {
    int midRow;

    if (target within midRow) {
        hasRow = true;
        rowIdx = midRow;
    }

    if (target < midRow[0]) {
        right = midRow - 1;
    } else if (target > midRow[size - 1]) {
        left = midRow + 1;
    }
}

if not found row: return false;

else, find within the row

*/
Enter fullscreen mode Exit fullscreen mode

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        boolean hasRow = false;
        int rowIdx = -1;

        int leftRow = 0;
        int rightRow = matrix.length - 1;
        int columns = matrix[0].length;

        while (leftRow <= rightRow) {
            int midRow = (leftRow + rightRow) / 2;

            if (target >= matrix[midRow][0] && target <= matrix[midRow][columns - 1]) {
                hasRow = true;
                rowIdx = midRow;
                break;
            } else if (target < matrix[midRow][0]) {
                rightRow = midRow - 1;
            } else if (target > matrix[midRow][columns - 1]) {
                leftRow = midRow + 1;
            }
        }

        if (!hasRow) {
            return false;
        }

        int left = 0;
        int right = columns - 1;

        while (left <= right) {
            int mid = (left + right) / 2;

            if (target == matrix[rowIdx][mid]) {
                return true;
            } else if (target < matrix[rowIdx][mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
truongductri01
truongductri01

Posted on October 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Leetcode Solution #6
coding Leetcode Solution #6

September 16, 2024

729. My Calendar I|| Leetcode || Medium
leetcode 729. My Calendar I|| Leetcode || Medium

September 27, 2024

2024-04-02: Prompt optimizations
devjournal 2024-04-02: Prompt optimizations

April 2, 2024

Learning DSA after 4 years of experience
beginners Learning DSA after 4 years of experience

January 17, 2024