【发布时间】:2013-11-10 20:45:20
【问题描述】:
最初,我使用了时间复杂度为 0(n^2) 的嵌套循环。为了更有效的 0(n),解决方案我编写了以下代码,并希望获得一些帮助/了解如何找出任何元素及其 .Next() 是否具有相同的值“重复”,如果是,请打印他们出去。
public class FindDuplicates {
public static void main(String arg[]){
int[] str={1 , 2 , 3 ,4 ,5 ,3 ,5 , 4,3,43,1,33,4,5};
List<Integer> list = new LinkedList<Integer>();
for(int x : str) {
list.add(x);
}
Collections.sort(list);
System.out.println(list);
Iterator<Integer> it = list.listIterator();
while(it.hasNext() && it.next() != null) {
/* Pseudocode => if(it.next().equals(it.next.next)); */
/* OR Pseudocode => if(it.next() == it.next().next) */
System.out.println(it) ;
}
}
}
【问题讨论】:
-
那么问题是什么?你想让你的代码被审查还是什么?
-
尝试定义一个名为
int lastEntry的变量。如果lastEntry != currentEntry则打印 currentEntry。这仅适用于排序列表。 -
在担心性能的情况下,您能说出为什么要使用
LinkedList吗?它内存效率低(每个列表项大约 8-16 个字节)、缓存效率低(堆上的数据)和算法受限(随机访问是 O(n)),并且仅有用用于一些非常特殊的用途。 -
@StackUnderFlow 您的方法很好,但您的解决方案取决于
collections.sort(),它的时间复杂度为nlog(n)。检查我的答案,它会给你O(n)时间复杂度。 -
@Prateek 您的 collections.sort() 确实如此,但此操作只会执行一次(对列表进行一次排序)。就时间复杂度而言,这仍然是可行的解决方案。“更好的坏选择”
标签: java arrays list linked-list