Some code review comments not mentioned by other:
- Unnecessary import:
You have import java.io.IOException;
but you are neither catching nor throwing an IOException
.
- Possible resource leak
When you open a Closable
resource, it is a good habit to .close()
it when you are done. This can be automatically done if you use a "try-with-resources" statement:
try (Scanner sc = new Scanner(System.in)) {
// ... use scanner in here
}
// Scanner is automatically closed here.
Better (or at least other) ways to solve the problem:
You can use a BitSet
to improve the time and space complexity of the algorithm. With 1 <= A[i] <= 500, the bit setBitSet
only needneeds 64 bytes of spacestorage. Setting and, clearing and (or inin this case toggling with .flip(bit)
) toggling bits are very fast O(1)\$O(1)\$ operations. You don't need to ask whether the element has been encountered before, adding it if it hasn't and removing it if is has; just flipping the corresponding bit performs the add-if-not-present and remove-if-present operations. This has to be done once per input value, resulting in \$O(n)\$. At the end, the sole remaining bit can be found with .nextSetBit(0)
, which is a \$O(n/64)\$ search operation, yielding an overall \$O(n)\$ algorithm.