Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save madsunrise/d6fadea1baa3dadc03aa8463a3e932d5 to your computer and use it in GitHub Desktop.
Save madsunrise/d6fadea1baa3dadc03aa8463a3e932d5 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] array = new int[n];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; ++i) {
int a = scanner.nextInt();
array[i] = a;
map.put(a, i);
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; ++i) {
int element = array[i];
if (map.get(element) != i) {
result.add(element);
}
}
System.out.println(result.size());
System.out.println(joinToString(result));
}
private static <T> String joinToString(Iterable<T> iterable) {
StringBuilder sb = new StringBuilder();
for (T item : iterable) {
sb.append(item.toString());
sb.append(" ");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment