这是我想要的解决方案,我已经包含了一个数组版本来测试它:
class ExpectationChecker
{
private final boolean[] results;
private final int min;
public ExpectationChecker(final int min, final int max)
{
this.results = new boolean[max - min + 1];
this.min = min;
}
public Integer[] getMissingNumbers(final ResultSet results) throws SQLException
{
while(results.next())
{
//Offset by min
this.results[results.getInt(1) - this.min] = true;
}
final List<Integer> missingNums = new ArrayList<>();
for(int i = 0; i < this.results.length; i++)
{
if(!this.results[i])
{
//Add min in case min isn't 0
missingNums.add(i + this.min);
}
}
return missingNums.toArray(new Integer[missingNums.size()]);
}
public Integer[] getMissingNumbers(final int[] results)
{
for(int i = 0; i < results.length; i++)
{
//Offset by min
this.results[results[i] - this.min] = true;
}
final List<Integer> missingNums = new ArrayList<>();
for(int i = 0; i < this.results.length; i++)
{
if(!this.results[i])
{
//Add min in case min isn't 0
missingNums.add(i + this.min);
}
}
return missingNums.toArray(new Integer[missingNums.size()]);
}
public static void main(String[] args)
{
final ExpectationChecker ec = new ExpectationChecker(10, 20);
final int[] test = {11, 12, 13, 14, 17, 19};
System.out.println(Arrays.deepToString(ec.getMissingNumbers(test)));
}
}
产生输出:
[10, 15, 16, 18, 20]