简体   繁体   English

在固定时间内在排序列表中查找索引

[英]Find index in sorted list in constant time

I have a set of custom objects I'm adding to a list and then sorting with a custom comparator. 我有一组自定义对象,要添加到列表中,然后使用自定义比较器进行排序。 I then have a second list of some subset of these objects which I need the index of in the first list so that I can find the objects which are equal (as defined by my comparator). 然后,我有了这些对象的一些子集的第二个列表,我需要在第一个列表中建立索引,以便可以找到相等的对象(由我的比较器定义)。 As the list is sorted these objects should simply be the objects directly before or after this object, but I don't know beforehand how many will be the same (likely 2-3). 在对列表进行排序时,这些对象应该只是该对象之前或之后的对象,但我事先不知道有多少个相同(可能是2-3个)。

I need this lookup to be in constant time as my list of sorted objects will be quite large. 我需要这种查找要保持恒定的时间,因为我排序的对象列表会很大。 I could obviously just use list.index(), but that will be O(N) and I think I can do better. 我显然可以只使用list.index(),但这将是O(N),我想我可以做得更好。 My first thought was to use a doubly linked list, but it looks like I would need to implement that myself and I'm not exactly sure how I would sort it. 我的第一个想法是使用双向链表,但看起来我需要自己实现,而且我不确定如何对它进行排序。

Is there a double linked list implementation in python? python中是否有双链表实现? Or is there a better alternative to this problem? 还是有解决这个问题的更好的选择? Also, I'm currently on python2.5 and can't update my version, but if I'm limited by my version I'm still interested in hearing about that solution. 另外,我目前使用的是python2.5,无法更新我的版本,但是如果我受我的版本的限制,我仍然会对听到该解决方案感兴趣。

For the price of additional O(N) storage, you might create a dictionary to back the list indices of the sorted list: 为了增加O(N)存储的价格,您可以创建一个字典来支持已排序列表的列表索引:

index_map = dict((e,i) for (i,e) in enumerate(sorted_list))

This would give you O(1) lookup for the position of items in your second list. 这将使您可以O(1)查找项目在第二个列表中的位置。

If the elements of sorted_list are custom objects, then, as @mseifert points out, this approach relies on the objects having __eq__ defined properly, and also being hashable. 如果sorted_list的元素是自定义对象,则正如@mseifert所指出的,此方法依赖于正确定义了__eq__且可哈希化的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM