-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathh.java
More file actions
67 lines (58 loc) · 2.19 KB
/
h.java
File metadata and controls
67 lines (58 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
class Solution {
// Function to find union of two sorted arrays using two pointers
public List<Integer> findUnion(int[] arr1, int[] arr2, int n, int m) {
// List to store union elements
List<Integer> Union = new ArrayList<>();
// Initialize pointers
int i = 0, j = 0;
// Iterate while both arrays have elements
while (i < n && j < m) {
// If element in arr1 is smaller
if (arr1[i] < arr2[j]) {
// Add if empty or not duplicate
if (Union.isEmpty() || Union.get(Union.size() - 1) != arr1[i])
Union.add(arr1[i]);
i++; // Move pointer in arr1
}
// If element in arr2 is smaller
else if (arr2[j] < arr1[i]) {
// Add if empty or not duplicate
if (Union.isEmpty() || Union.get(Union.size() - 1) != arr2[j])
Union.add(arr2[j]);
j++; // Move pointer in arr2
}
else {
// Elements are equal, add once if not duplicate
if (Union.isEmpty() || Union.get(Union.size() - 1) != arr1[i])
Union.add(arr1[i]);
i++; j++; // Move both pointers
}
}
// Append remaining elements from arr1
while (i < n) {
if (Union.isEmpty() || Union.get(Union.size() - 1) != arr1[i])
Union.add(arr1[i]);
i++;
}
// Append remaining elements from arr2
while (j < m) {
if (Union.isEmpty() || Union.get(Union.size() - 1) != arr2[j])
Union.add(arr2[j]);
j++;
}
// Return the union list
return Union;
}
}
public class h {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = {2, 3, 4, 4, 5, 11, 12};
int n = arr1.length, m = arr2.length;
Solution obj = new Solution();
List<Integer> result = obj.findUnion(arr1, arr2, n, m);
System.out.print("Union of arr1 and arr2 is: ");
for (int val : result) System.out.print(val + " ");
}
}