假设您仅限于使用原始类型而不是能够使用java.util.Collections
,您可以像这样工作:
For each value in `x`
Grab that value
If the list of duplicates does not contain that value
See if that value reoccurs at a later index in `x`
If it does, add it to the list of duplicates
这是翻译成Java的伪代码:
private void example() {
int [] x = new int [] {1,2,199,100,8,100,199,1001,5,9, 199};
int [] duplicates = new int[x.length];
for (int i = 0; i < x.length; i++) {
int key = x[i];
if (!contains(duplicates, key)) {
// then check if this number is a duplicate
for (int j = i+1; j < x.length-1; j++) {
// start at index i+1 (no sense checking same index as i, or before i, since those are alreayd checked
// and stop at x.length-1 since we don't want an array out of bounds exception
if (x[j] == key) {
// then we have a duplicate, add to the list of duplicates
duplicates[i] = key;
}
}
}
}
for (int n = 0; n < duplicates.length; n++) {
if (duplicates[n] != 0) {
System.out.println(duplicates[n]);
}
}
}
private boolean contains(int [] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return true;
}
}
return false;
}