Skip to content

Commit 5d901e4

Browse files
solves search in 2d matrix ii in java
1 parent 9ca4b0a commit 5d901e4

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@
193193
| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) | [![Java](assets/java.png)](src/LowestCommonAncestorOfBinaryTree.java) | |
194194
| 237 | [Delete a Node In A Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list) | [![Java](assets/java.png)](src/DeleteANodeInLinkedList.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | |
195195
| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self) | [![Java](assets/java.png)](src/ProductOfArrayExceptItself.java) | |
196-
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | | |
196+
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | [![Java](assets/java.png)](src/SearchA2DMatrixII.java) | |
197197
| 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses) | | |
198198
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram) | [![Java](assets/java.png)](src/ValidAnagram.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | |
199199
| 243 | 🔒 [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) | | |

Diff for: src/SearchA2DMatrixII.java

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// https://leetcode.com/problems/search-a-2d-matrix-ii
2+
// T: O(m + n)
3+
// S: O(1)
4+
5+
public class SearchA2DMatrixII {
6+
public boolean searchMatrix(int[][] matrix, int target) {
7+
final int rows = matrix.length, columns = matrix[0].length;
8+
for (int column = columns - 1, row = 0 ; row < rows && column >= 0 ; ) {
9+
if (matrix[row][column] == target) return true;
10+
else if (matrix[row][column] < target) row++;
11+
else column--;
12+
}
13+
return false;
14+
}
15+
}

0 commit comments

Comments
 (0)