gpt4 book ai didi

java - 删除数组中的冗余值

转载 作者:行者123 更新时间:2023-12-01 14:01:15 26 4
gpt4 key购买 nike

我不确定为什么我的removeDuplicates方法拒绝真正删除非唯一值。我不确定问题是否出在大小增量或我的方法调用上。

// post: places the value in the correct place based on ascending order
public void add(int value) {
size++;
if (size == 1) {
elementData[0] = value;
} else {
int position = Arrays.binarySearch(elementData, 0, size - 1, value);
if (position < 0 ) {
position = (-position) - 1;
}
for (int i = size - 1; i > position; i--) {
elementData[i] = elementData[i - 1];
}
elementData[position] = value;
}
if (unique) {
removeDuplicates();
}
}

//post: removes any duplicate values from the list
private void removeDuplicates() {
for(int i = size - 1; i > 0; i--) {
if (elementData[i] == elementData[i - 1]){
remove(i - 1);
}
}
}

最佳答案

@user98643-

Jano 的建议是完全正确的:最好的解决方案是简单地使用适当的数据结构,例如 TreeSet .

建议:

1) 一般来说,总是考虑使用“List<>”等容器而不是数组

2)一般来说,寻找已经拥有您需要的大部分属性的容器

3) 在这种情况下,A) 您希望对所有元素进行排序,并且 B) 每个元素必须是唯一的。

TreeSet 非常适合这个要求。

恕我直言..

http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

http://math.hws.edu/javanotes/c10/s2.html

http://www.mkyong.com/java/what-is-the-different-between-set-and-list/

关于java - 删除数组中的冗余值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com