I am trying to solve a problem :
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.
Input: matrix =
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
The code that I have written is :
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int i,j;
for(i = 0; i < m; i++)
{
if(target >= matrix[i][0] && target <= matrix[i][n-1])
{
break;
}
}
for(j = 0; j < n; j++)
{
if(matrix[i][j] == target)
{
return true;
}
}
return false;
}
}
I am getting this error :
Runtime Error Message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Solution.searchMatrix(Solution.java:4)
at __DriverSolution__.__helper__(__Driver__.java:8)
at __Driver__.main(__Driver__.java:54)
Last executed input:
[]
0