Write a java program to find intersection of elements in two arrays in java

preview_player
Показать описание
This video explains how to find intersection of elements in 2 arrays in java.
Рекомендации по теме
Комментарии
Автор

all your solutions are containing the collections/ using some apis. generally interviewer asks for solutions without using any datastructures.

srinivasgangaraju
Автор

public class InterSection {

public static void main(String[] args) {
int arr1[]= {4, 1, 2, 3};
int arr2[]= {5, 4, 2, 8};
of the Two Arrays:: ");

for(int i=0; i<arr1.length; i++) {
for(int j=0; j<arr2.length; j++) {
if(arr1[i]==arr2[j]) {
System.out.println(arr1[i]);
}
}
}
}

}

svr
Автор

Another approach
1. Add array1 to hashset1
2. Add array2 to hashset2
3. Hashset1.retainAll(hashset2)

We can use the below also but it will add the second array element into hashset
if(!hashset.add(arrElement))

vengateshm
Автор

Most of the time they'll say don't use any built in method to solve the problem.

for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
return arr2[j];
}
}
}

manimaran
Автор

Hi,
What is the purpose of using hashset here. Please let me know

sarathvarada
Автор

if there are dublicate elements while we are adding elements to the hashset what should we do?

karthikreddypakala
join shbcf.ru