- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathIntersectionOfTwoArrays.java
52 lines (41 loc) · 1.09 KB
/
IntersectionOfTwoArrays.java
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
importjava.util.ArrayList;
importjava.util.Arrays;
publicclassIntersectionOfTwoArrays {
publicstaticvoidmain(String[] args) {
}
staticint[] intersection(int[] nums1, int[] nums2) {
if(nums1.length > nums2.length){
returnintersection(nums2, nums1);
}
ArrayList<Integer> list = newArrayList<>();
Arrays.sort(nums1);
for(intnum : nums2){
if(bS(nums1, num)){
if(!list.contains(num)){
list.add(num);
}
}
}
int[] ans = newint[list.size()];
for(inti = 0 ; i < list.size() ; i++){
ans[i] = list.get(i);
}
returnans;
}
staticbooleanbS(int[] arr, inttarget){
ints = 0;
inte = arr.length-1;
while(s <= e){
intm = s + (e-s)/2;
if(arr[m] == target){
returntrue;
}
if(arr[m] < target){
s = m+1;
} else{
e = m-1;
}
}
returnfalse;
}
}