File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments