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<Integer> findIt (int[] a, int[] b){
ArrayList<Integer> result = new ArrayList<Integer>();
Arrays.sort(a);
Arrays.sort(b);
int i = 0;
int j = 0;
while(i < a.length && j < b.length){
if(a[i]<b[j])
++i;
else if (a[i] > b[j])
++j;
else{
if (!result.contains(a[i]))
result.add(a[i]);
++i;
++j;
}
}
return result;
}
List
s instead of arrays as input, I'll ask directly: Any special reason you are using arrays? It's very unusual to use arrays in Java, becauseList
s are much more flexible. Generally, unless you need to optimize extremely for speed, you should reconsider using arrays at all. – RoToRa Mar 13 '12 at 9:42