Using 2 pointers
This method does not need to use any containers
, and does not need to create the array space. It is recommended, but the position information between the array elements is lost.
- Sort the array first;
- Initialize two pointers p, q to traverse the sorted array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public static void solution(int[] array){
Arrays.sort(array);
int p = 0, q = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] != array[i+1]) {
if (p < q) {
array[p+1] = array[q+1];
p ++;
q ++;
} else {
p = i + 1;
}
} else {
q = i + 1;
}
}
for (int i = 0; i <= p; i++) {
System.out.print(array[i] + " ");
}
System.out.println("length = " + (p+1));
}
|
Using Set
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Set set = new HashSet<>();
for(int i = 0; i < array.length; ++i){
set.add(array[i]);
}
int m = 0;
for(Iterator iterator = set.iterator(); iterator.hasNext();){
array[m] = (int)iterator.next();
m++;
}
for(int j = 0; j < set.size(); ++j){
System.out.print(array[j] + " ");
}
System.out.println();
System.out.println("length = " + set.size());
|
Using List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
List list = new ArrayList<>();
for(int i = 0; i < array.length; ++i){
if(!list.contains(array[i]))
list.add(array[i]);
}
for(int i = 0; i < list.size(); ++i){
array[i] = (int)list.get(i);
}
for(int i = 0; i < list.size(); ++i){
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("length = " + list.size());
|