Lookup in a two-dimensional array
Title description
In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right , and each column is sorted in increasing order from top to bottom . Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.
Solution 1: Violence
function Find(target, array)
{
if(array.length == 0 || target == null) return false;
for(let i = 0; i < array.length; i++){
for(let j = 0; j < array[0].length ; j++){
if(array[i][j] == target) return true;
}
}
return false;
}
Time complexity: O(N 2 )
Space complexity: O(1)
Solution two:
According to the requirements of the title, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. You can use this feature to search based on data.
- From top to bottom in the rightmost column, find a number that is not less than the target, and then search from right to left. The target is either in this row or not found.
function Find(target, array)
{
if(array.length == 0 || target == null) return false;
let i = 0,
j = array[0].length - 1;
while(i < array.length && j >= 0){
if(array[i][j] == target) return true;
if(array[i][j] > target) j--;
else i++;
}
return false;
}
Time complexity: O(M + N) (row height + column height)
Space complexity: O(1)
Other solutions
The same idea as the second solution, starting from a certain corner, remove one line for each comparison until a matching line is found, and then search in that line.