Skip to content

Instantly share code, notes, and snippets.

@Ram-1234
Last active January 4, 2021 11:31
Show Gist options
  • Save Ram-1234/3b621a524f1ecbf6ce5a1186feb400b8 to your computer and use it in GitHub Desktop.
Save Ram-1234/3b621a524f1ecbf6ce5a1186feb400b8 to your computer and use it in GitHub Desktop.
serach target int value in matrix
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Searchtarget
{
public static boolean searchTarget(int[][] matrix,int target){
if(matrix.length==0 || matrix[0].length==0)
return false;
int m=matrix.length; // Find Out Row Length
int n=matrix[0].length; // Find Out Clumn Length
for(int i=0;i<m;i++)
{
if(target>matrix[i][n-1]) continue;
int s=0,e=n-1;
while(s<=e){ //I Am Here Use Binary Search
int mid=(int)(s+e)/2;
if(matrix[i][mid]==target) return true;
else if(matrix[i][mid]<target) s=mid+1;
else
e=mid-1;
}
}
return false;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int m=in.nextInt();
int n=in.nextInt();
int t=in.nextInt();
int arr[][] = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
arr[i][j]=in.nextInt();
}
}
System.out.println(searchTarget(arr,t));
}
}
////////
Overa All complexity is=O(mlogn)
NIPUT VALUE
3
4
16
1 3 5 7
10 11 16 20
23 30 34 60
OUTPUT
true
NOTE:-We Can Also Solve This Problem In O(n2) In Time Using Loop
@Ram-1234
Copy link
Author

good explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment