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;
}
I would like any advice on how to improve the code above. 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]. Any improvements should make the code more readable or perform faster.
Thank you for your advice.
Lists 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, becauseLists 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