LeetCode 240: Search a 2D Matrix II Solution
Master LeetCode problem 240 (Search a 2D Matrix II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
240. Search a 2D Matrix II
Problem Explanation
Explanation
To solve this problem efficiently, we can start from the top right corner of the matrix. If the target is smaller than the current element, we move left since all elements in the current row are greater. If the target is larger, we move down since all elements in the current column are smaller. By following this approach, we can eliminate rows and columns at each step and eventually find the target or determine it doesn't exist.
-
Algorithm:
- Start from the top right corner.
- If the target is smaller, move left.
- If the target is larger, move down.
- Repeat until the target is found or the current position is out of bounds.
-
Time Complexity: O(m + n) - where m is the number of rows and n is the number of columns.
-
Space Complexity: O(1) - constant space is used.
Solution Code
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = 0, col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 240 (Search a 2D Matrix II)?
This page provides optimized solutions for LeetCode problem 240 (Search a 2D Matrix II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 240 (Search a 2D Matrix II)?
The time complexity for LeetCode 240 (Search a 2D Matrix II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 240 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 240 in Java, C++, or Python.