patternjavaMinor
Finding the Intersection of Arrays
Viewed 0 times
intersectionthearraysfinding
Problem
I would like any advice on how to improve this code. To clarify what this code considers an intersection to be, the intersection of [3,3,4,6,7] and [3,3,3,6,7] is [3,6,7]. I would appreciate any improvements to make the code more readable or perform faster.
public ArrayList findIt (int[] a, int[] b){
ArrayList result = new ArrayList();
Arrays.sort(a);
Arrays.sort(b);
int i = 0;
int j = 0;
while(i b[j])
++j;
else{
if (!result.contains(a[i]))
result.add(a[i]);
++i;
++j;
}
}
return result;
}Solution
Algorithm
You're using a O(n log(n)) algorithm here, which could be O(n²) for difficult cases since
See my tested code for my implementation:
Comments on your code
You're using a O(n log(n)) algorithm here, which could be O(n²) for difficult cases since
contains() is O(n) and is called in a loop. Instead, use the property of HashSet: access is O(1), which means you can achieve this in O(n) time. My algorithm below simply keeps track of what it can add to the result. I can add everything that exists in the first list, but I should not add an item I already added.See my tested code for my implementation:
public static List intersection(List a, List b){
Set canAdd = new HashSet(a);
List result = new ArrayList();
for (int n: b) {
if(first.contains(n)) {
result.add(n);
// we wish to add only one n
canAdd.remove(n);
}
}
return result;
}Comments on your code
- You should return a
List, not anArrayListsince it's an implementation detail. Using anArrayListis OK here since adding at the end of it has O(1) amortized complexity. Otherwise, lists should beLinkedList(when adding to the beginning, not to the end, as @Landei points out).
- Be careful about the names you choose.
findItdoesn't seem to be appropriate, butremoveDuplicatesorintersectiondescribes what the code does.
Code Snippets
public static List<Integer> intersection(List<Integer> a, List<Integer> b){
Set<Integer> canAdd = new HashSet<Integer>(a);
List<Integer> result = new ArrayList<Integer>();
for (int n: b) {
if(first.contains(n)) {
result.add(n);
// we wish to add only one n
canAdd.remove(n);
}
}
return result;
}Context
StackExchange Code Review Q#9909, answer score: 8
Revisions (0)
No revisions yet.