Java 试图消除阵列中的重复项但不起作用
从技术上讲,这是一个硬件作业,但我做它是为了练习,而不是为了分数。到目前为止,我的解决方案存在以下问题:Java 试图消除阵列中的重复项但不起作用,java,Java,从技术上讲,这是一个硬件作业,但我做它是为了练习,而不是为了分数。到目前为止,我的解决方案存在以下问题: /** * smoosh() takes an array of ints. On completion the array contains the * same numbers, but wherever the array had two or more consecutive * duplicate numbers, they are replaced
/**
* smoosh() takes an array of ints. On completion the array contains the
* same numbers, but wherever the array had two or more consecutive
* duplicate numbers, they are replaced by one copy of the number. Hence,
* after smoosh() is done, no two consecutive numbers in the array are the
* same.
*
* Any unused elements at the end of the array are set to -1.
*
* For example, if the input array is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], it
* reads [ 0 1 0 3 1 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 ] after smoosh()
* completes.
*
* @param ints
* the input array.
**/
public static void smoosh(int[] ints) {
// Fill in your solution here. (Ours is fourteen lines long, not
// counting
// blank lines or lines already present in this file.)
int index = ints.length - 1;
for (int i = 1; i < ints.length; i++) {
if (ints[i] == ints[i - 1]) {
for (int j = i; j < ints.length - 1; j++) {
ints[j] = ints[j + 1];
}
ints[index] = -1;
index--;
}
}
}
我离得有点近了,但它仍然不能正常工作,所以我的逻辑肯定有问题也许你应该看看如何使用集合。请看下面的图片 我会按以下方法处理你的问题:
集
对象public Integer deduplicateArray(int[] values) {
Set<Integer> intSet = new HashSet<>(values.length);
for(Integer i : values) {
if(!intSet.add(i))
System.out.println("Value " + i + " is duplicated and was not added");
}
return intSet.toArray();
}
一些有用的链接:
希望这对您有所帮助。例如,您可以按以下方式执行:
int[] array = {0, 1, 0, 3, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1};
Set<Integer> set = new TreeSet<>();
for (int i : array) {
set.add(i);
}
System.out.println("set = " + set);
如果a==b,那么a=b;//没用,你不这么认为吗?你设置了相同的值,所以本质上你的循环没有做任何事情…我让增量工作,但出于某种原因,它跳过了一些重复项
// ...
int aValue; // This is a int (primitive) variable
Integer someInteger = 12; // This is an Integer object
aValue = someInteger + 3; // aValue is still a `int` (primitive) variable
// ...
int[] array = {0, 1, 0, 3, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1};
Set<Integer> set = new TreeSet<>();
for (int i : array) {
set.add(i);
}
System.out.println("set = " + set);
set = [-1, 0, 1, 3]