【发布时间】:2017-11-02 13:02:44
【问题描述】:
如果整数(或其他对象)像这样,我们有列表:
[0, 0, 1, 1, ... , 777777, ... , 999999, 999999]
Java 代码:
List<Integer> ints = new LinkedList<Integer>();
for (int i = 0; i < 999999; i++) {
ints.add(i); // add first value
if (i!=777777){
ints.add(i); // add duplicate value in not '5'
}
}
我就是这样解决这个问题的:
Integer unique = null;
while (true) {
unique = ints.get(0);
ints.remove(0);
if (ints.contains(unique)) {
ints.remove(ints.indexOf(unique));
} else {
break;
}
}
System.out.println(unique);// 777777
大约需要 30 毫秒。使用 ArrayList,它的工作时间会更长。 问题是如何以最佳(正确/优雅/最快)的方式从此列表中获取一个唯一值(例如 777777)。
【问题讨论】:
-
1.对列表进行排序 2. 迭代并检查每个项目与上一个和下一个项目是否是唯一的。
-
如果您知道元素是成对出现的(唯一的除外),请使用二分搜索来查找这些对出现在偶数索引和奇数索引之间的边界,以及它们进入的位置奇数,然后是偶数索引。与
ArrayList一起工作很快。 -
相等的元素是否总是连续出现在列表中?
-
优雅和快速是有区别的。你喜欢哪个?在我耳边,30 毫秒听起来没什么问题。