-
Notifications
You must be signed in to change notification settings - Fork 0
/
intersection1.java
80 lines (61 loc) · 1.96 KB
/
intersection1.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
public class intersection1 {
public static int[] intersection(int[] num1, int[] num2) {
int[] newArr;
int[] newArr2;
int[] resultArr;
if(num1.length<=num2.length){
newArr = removeRepeating(num1);//arr
newArr2 = num2;
}
else{
newArr = removeRepeating(num2);//arr
newArr2 = num1;
}
resultArr = new int[newArr.length];
for(int i = 0;i<resultArr.length;i++){
resultArr[i]=-1;
}
for(int i =0;i<newArr.length;i++){
for(int j = 0;j<newArr2.length;j++){
if(newArr[i]==newArr2[j]){
resultArr[i] = newArr[i];
}
}
}
return resizing(resultArr);
}
public static int[] removeRepeating(int[] num){
for(int i = 0;i<num.length;i++){
for(int j = i+1;j<num.length;j++){
if(num[i]==num[j])
num[j]=-1 ;
}
}
return resizing(num);
}
public static int[] resizing(int[] temp){
int count = 0;
int[] arr;
for(int i = 0;i<temp.length;i++){
if(temp[i]>-1)
count++;
}
arr = new int[count];
for(int i = 0;i<temp.length;i++){
if(temp[i]>-1){
arr[arr.length-count] = temp[i];
count--;
}
if(count<0)
break;
}
return arr;
}
public static void main(String[] args){
int[] num1 = {1,2,2,1};
int[] num2 = {2,2};
int[] result = intersection(num1,num2);
System.out.println(Arrays.toString(result));
}
}