add static intersection method for sorted lists

This commit is contained in:
2017-12-03 09:59:58 +01:00
parent ba51b62a53
commit c41e52f8b3
2 changed files with 72 additions and 1 deletions

View File

@@ -20,7 +20,7 @@ public final class IntList implements Serializable, Cloneable {
// TODO support sublists
// TODO add lastIndexOf
// TODO remove bounds checks that are handled by java, e.g. negative indices
// TODO clear
// TODO intersection for unsorted lists
private static final long serialVersionUID = 2622570032686034909L;
@@ -367,6 +367,7 @@ public final class IntList implements Serializable, Cloneable {
* @see #trim()
*/
public void retainAll(final IntList retain) {
int insertPosition = 0;
for (int i = 0; i < size; i++) {
final int current = data[i];
@@ -702,4 +703,47 @@ public final class IntList implements Serializable, Cloneable {
}
}
/**
* Returns a list with all elements that are in {@code a} and {@code b}.
* <p>
* The cardinality of each element will be equal to the minimum of the
* cardinality of each element in the given lists.
*
* @param a
* a sorted {@link IntList}
* @param b
* a sorted {@link IntList}
* @return {@link IntList} containing all elements that are in {@code a} and
* {@code b}
* @throws NullPointerException
* if {@code a} or {@code b} is null
*/
public static IntList intersection(final IntList a, final IntList b) {
final IntList result = new IntList(Math.min(a.size(), b.size()));
if (a.isSorted() && b.isSorted()) {
int l = 0;
int r = 0;
while (l < a.size() && r < b.size()) {
final int lv = a.get(l);
final int rv = b.get(r);
if (lv < rv) {
l++;
} else if (lv > rv) {
r++;
} else {
result.add(lv);
l++;
r++;
}
}
} else {
throw new UnsupportedOperationException("retainAll on unsorted lists is not yet supported");
}
return result;
}
}