Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4184325

Browse files
Add implementation for Intersection and Union of Two Arrays using HashSet
1 parent 7e4abf0 commit 4184325

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
import java.util.HashSet;
3+
4+
// intput -> arr1[] = {1,2,3,4,5,6,7,8,9} ;
5+
// arr2[] ={2,3,3,4,4,4,4,4,10};
6+
7+
// commonly in both arrays.
8+
9+
// output: [2,3,4]
10+
11+
12+
13+
public class IntersectionOfTwoArrays {
14+
public static void main(String[] args) {
15+
int arr1[] = {1,2,3,4,5,6,7,8,9};
16+
int arr2[] ={2,3,3,4,4,4,4,4,10,5};
17+
18+
FindIntersection(arr1, arr2);
19+
20+
}
21+
22+
public static void FindIntersection(int arr1[], int arr2[]){
23+
HashSet <Integer> set = new HashSet<>();
24+
HashSet <Integer> result = new HashSet<>();
25+
26+
for (int num : arr1) {
27+
set.add(num);
28+
}
29+
30+
// check intersection
31+
32+
for (int num : arr2) {
33+
if(set.contains(num))
34+
result.add(num);
35+
}
36+
37+
//Print the result
38+
System.out.print("Intersection: ");
39+
for (int value : result) {
40+
System.out.println(value);
41+
}
42+
}
43+
}

‎Hashing/Question/UnionOfTwoArrays.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
import java.util.HashSet;
3+
4+
public class UnionOfTwoArrays {
5+
public static void main(String[] args) {
6+
int arr1[] = { 1, 2, 3, 4, 5, 6 };
7+
int arr2[] = { 1, 2, 4 ,10};
8+
9+
int result = FindUnion(arr1, arr2);
10+
System.out.println("The union of the two arrays is: " + result); // (result -> 1,2,3,4,5,6,10) size -> 7
11+
}
12+
13+
public static int FindUnion(int arr1[], int arr2[]) {
14+
15+
HashSet<Integer> set = new HashSet<>();
16+
17+
// for arr1
18+
for (int num : arr1) {
19+
set.add(num);
20+
}
21+
22+
// for arr2
23+
for (int num : arr2) {
24+
set.add(num);
25+
}
26+
27+
return set.size();
28+
}
29+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /