Last active
January 4, 2021 11:31
-
-
Save Ram-1234/3b621a524f1ecbf6ce5a1186feb400b8 to your computer and use it in GitHub Desktop.
serach target int value in matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good explanation