g0001_0100.s0074_search_a_2d_matrix.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0074_search_a_2d_matrix;
// #Medium #Top_100_Liked_Questions #Array #Binary_Search #Matrix #Data_Structure_I_Day_5_Array
// #Algorithm_II_Day_1_Binary_Search #Binary_Search_I_Day_8 #Level_2_Day_8_Binary_Search
// #Udemy_2D_Arrays/Matrix #Big_O_Time_O(endRow+endCol)_Space_O(1)
// #2023_08_11_Time_0_ms_(100.00%)_Space_40.9_MB_(71.91%)
/**
* 74 - Search a 2D Matrix\.
*
* Medium
*
* Write an efficient algorithm that searches for a value in an `m x n` matrix. This matrix has the following properties:
*
* * Integers in each row are sorted from left to right.
* * The first integer of each row is greater than the last integer of the previous row.
*
* **Example 1:**
*
* ![](https://assets.leetcode.com/uploads/2020/10/05/mat.jpg)
*
* **Input:** matrix = \[\[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
*
* **Output:** true
*
* **Example 2:**
*
* ![](https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg)
*
* **Input:** matrix = \[\[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
*
* **Output:** false
*
* **Constraints:**
*
* * `m == matrix.length`
* * `n == matrix[i].length`
* * `1 <= m, n <= 100`
* * -104 <= matrix[i][j], target <= 104
**/
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int endRow = matrix.length;
int endCol = matrix[0].length;
int targetRow = 0;
boolean result = false;
for (int i = 0; i < endRow; i++) {
if (matrix[i][endCol - 1] >= target) {
targetRow = i;
break;
}
}
for (int i = 0; i < endCol; i++) {
if (matrix[targetRow][i] == target) {
result = true;
break;
}
}
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy