Skip to content

Commit ffa8d6c

Browse files
Merge pull request #132 from niranjana687/patch-2
Create Search2DMatrix.java
2 parents cd3d03b + 07325db commit ffa8d6c

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

LeetCode/Search2DMatrix.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//Solution to https://leetcode.com/problems/search-a-2d-matrix/submissions/
2+
3+
//Approach: An element in the matrix can be accessed by matrix[i/c][i%c] where c is the number of columns.
4+
//We check if the element matches the target during traversal. If yes it return true.
5+
//In case where the current element in matrix is greater than target, we return false.
6+
//This is because the matrix is sorted and if the value is greater it implies that the target element does not exist.
7+
8+
9+
class Solution {
10+
public boolean searchMatrix(int[][] matrix, int target) {
11+
12+
int c = matrix[0].length;
13+
int r = matrix.length;
14+
15+
for(int i=0; i< c*r; i++) {
16+
if (matrix[i/c][i%c] == target) return true;
17+
else if (matrix[i/c][i%c] > target) return false;
18+
}
19+
return false;
20+
}
21+
}

0 commit comments

Comments
 (0)