0% found this document useful (0 votes)
5 views3 pages

Efficient 2D Matrix Search Algorithm

Uploaded by

pawan.sahu.2027
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Efficient 2D Matrix Search Algorithm

Uploaded by

pawan.sahu.2027
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// write your code here...// write your code here...

/*
Imagine a 2D matrix where the rows and columns are sorted. Your task is to design
an
efficient algorithm to find a specific target value within this matrix.
Design a function named `searchMatrix` to implement this algorithm.

Example 1:
Input:
matrix = [
[1, 3, 7, 11],
[2, 4, 5, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
]
target = 5
Output:
True

Example 2:
Input:
matrix = [
[1, 3, 7, 15],
[2, 4, 8, 17],
[3, 5, 9, 19],
[10, 12, 14, 23]
]
target = 10
Output:
true
-------------------------------------------------
// write your code here...// write your code here...

/*
Imagine a 2D matrix where the rows and columns are sorted. Your task is to design
an
efficient algorithm to find a specific target value within this matrix.
Design a function named `searchMatrix` to implement this algorithm.

Example 1:
Input:
matrix = [
[1, 3, 7, 11],
[2, 4, 5, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
]
target = 5
Output:
True

Example 2:
Input:
matrix = [
[1, 3, 7, 15],
[2, 4, 8, 17],
[3, 5, 9, 19],
[10, 12, 14, 23]
]
target = 10
Output:
true

NxM

1 <= N,M < 10^6

-10^8 <= matrix[i,j] <= 10^82

*/

public int searchMAtrix (ArrayList<ArrayList<Integer>> A, int B){


int N = [Link]() ;
int M = [Link](0).size() ;
int i = 0;
int j = N -1;
while ( i < M && j >= 0){
int temp = [Link](i).get(j);
if (temp == B){
return 1;
}
if (temp > B){
j--;
}
else {
i++;
}
}
return -1;
}

You might also like