I need to write a method that takes 2d array \'int [][] m\' and a value \'val\' and check if val is in the array in the complexity of O(n) while n defined as the num
Smth. like that. In case of Every number at row i
is equals or smaller then every number on row i+1
, than you can check only first element in each row to define a row, where required value could be. Element in unsorted row can be found only with full scan.
This algorithm have to scan 2 full rows only, which is O(n) where n - number of rows.
public static boolean findValTest(int[][] m, int val) {
for (int row = 0; row < m.length; row++) {
if (m[row][0] <= val && row != m.length - 1)
continue;
int r = row;
while (r >= row - 1 && r >= 0) {
for (int col = 0; col < m[r].length; col++)
if (m[r][col] == val)
return true;
r--;
}
return false;
}
return false;
}
Test cases:
System.out.println(findValTest(arr3, -1)); // false
System.out.println(findValTest(arr3, 5)); // true
System.out.println(findValTest(arr3, 7)); // true
System.out.println(findValTest(arr3, 55)); // false
System.out.println(findValTest(arr3, 47)); // true
System.out.println(findValTest(arr3, 147)); // true
System.out.println(findValTest(arr3, 200)); // false
System.out.println(findValTest(new int[][] { { 3, 4, 5 } }, 4)); // true