[英]Get the smallest difference between elements in a data structure in less than O(n) time
Say I have some integers in a data structure. 假设我在数据结构中有一些整数。 When I insert new number into the data structure, I want to get the smallest difference between the new inserted elements and any other elements already in the data structure.
当我在数据结构中插入新数字时,我希望获得新插入的元素与数据结构中已有的任何其他元素之间的最小差异。 What data structure and algorithm should I use?
我应该使用什么数据结构和算法? AO(n) solution is trivial and I want better.
AO(n)解决方案很简单,我想要更好。 Thanks.
谢谢。
One option would be to use a TreeSet
(based on TreeMap
), which would require several O(lg n)
operations. 一种选择是使用
TreeSet
(基于TreeMap
),这将需要几个O(lg n)
操作。 The class exposes two methods which can be used to find the element which is closest to the value you wish to insert: 该类提供了两种方法,可用于找到最接近您要插入的值的元素:
public E ceiling(E e)
公共E上限(E e)
Returns the least element in this set greater than or equal to the given element, or null if there is no such element.返回此集合中大于或等于给定元素的最小元素;如果没有此类元素,则返回null。
public E floor(E e)
公共E楼(E e)
Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.返回此集合中小于或等于给定元素的最大元素;如果没有此类元素,则返回null。
public static int findClosest(TreeSet set, Integer val) {
if (set == null || set.size() == 0) {
return -1;
}
// ceiling == 9 for input of 7
// O(lg n) operation
Integer ceiling = (Integer)set.ceiling(val);
// floor = 6 for input of 7
// O(lg n) operation
Integer floor = (Integer)set.floor(val);
if (ceiling == null) {
return val - floor;
}
if (floor == null) {
return ceiling - val;
}
return (val - floor > ceiling - val) ? ceiling - val : val - floor;
}
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
ts.add(5);
ts.add(1);
ts.add(6);
ts.add(9);
ts.add(2);
ts.add(3);
int diff = findClosest(ts, 7);
// closest is 6, so diff == 1
}
You could use a height-balanced binary search tree . 您可以使用高度平衡的二进制搜索树 。 These can be implemented with one of a number of data structures.
这些可以用许多数据结构之一来实现。 Insertions are usually O(log(n)) on average and looking up the one or two closest integers (on either side of the inserted value) will also be at most O(log(n)).
插入通常平均为O(log(n)),查找一个或两个最接近的整数(在插入值的任一侧)也最多为O(log(n))。
There may be other data structures that can do better (particularly if you can reasonably bound the integer values you need to deal with), but I can't think of one off the top of my head. 可能还有其他数据结构可以做得更好(特别是如果您可以合理地绑定需要处理的整数值),但是我想不到一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.