
ayuda con arrays
Publicado por giant (1 intervención) el 22/09/2016 18:34:15
Buenas estoy implementando un metodo compactar que compacta los elementos
consecutivos iguales a una unica aparicion.
ejemplo : compactar({2,2,1,2}) ---{2,1,2}
Esto es lo que he conseguido hacer hasta el momento y no se como hacer que sean consecutivos.
consecutivos iguales a una unica aparicion.
ejemplo : compactar({2,2,1,2}) ---{2,1,2}
Esto es lo que he conseguido hacer hasta el momento y no se como hacer que sean consecutivos.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Arrays;
public class test {
private static int[] removeDupes(int[] array) {
if (array == null) {
throw new IllegalArgumentException();
}
int end = array.length - 1;
for (int i = 0; i <= end; i++) {
for (int j = i + 1; j <= end; j++) {
if (array[i] == array[j]) {
while (end >= j && array[j] == array[end]) {
end--;
}
if (end > j) {
array[j] = array[end];
end--;
}
}
}
}
return Arrays.copyOf(array, end + 1);
}
public static void main(final String[] args) {
System.out.println(Arrays.toString(removeDupes(new int[] { 3, 45, 1, 2, 4,3, 3, 3, 3, 2, 1, 45, 2, 10 }))); //sale 3,45,1,2,4,10 en vez de 3,45,1,2,4,3,2,1,45,2,10
System.out.println(Arrays.toString(removeDupes(new int[] { 2, 2, 3, 3 })));
System.out.println(Arrays.toString(removeDupes(new int[] { 1, 1, 1, 1, 1, 1, 1, 1 })));
System.out.println(Arrays.toString(removeDupes(new int[] {})));
System.out.println(Arrays.toString(removeDupes(new int[] {1})));
}
}
Valora esta pregunta


0