简体   繁体   中英

Data structure with fast indexOf?

I need an ordered data structure with O(1) indexOf operation. I store object pointers in the data structure. Any ideas? Some sort of LinkedHashMap?

See what "indexOf" means: List.indexOf(Object)

This question is ambiguous to begin with.

  1. It would be nice if you could qualify what you mean by fast indexOf(..) operation.
  2. What kind of objects are you going to store in the collection?
  3. Is finding the indexOf(..) the only responsibility of the collection.

Simply put, one way to do this would be to maintain a that would index each Object or keys with the list of indices.

HashMap<Object, List<Integer>>

Again, this is vague, probably would help if you specify the exact nature of problem you're trying to solve.

Sounds like you want a SortedMap , TreeMap being the reference implementation. The performance is log(n) , and that's probably the best you are going to get using lookup in an ordered structure (at least in standard libraries).

If you use a skip list or a balanced tree, you can get O(log n) for insert and indexOf .

If you maintain a sorted List<Object> to store the items you want to track, along with a HashMap<Object, Integer> to store the starting position of each item, you can get O(1) indexOf in exchange for O(n) insert .

I haven't thought about it deeply, but I don't think it's possible to get O(1) insert and O(log n) indexOf.

尝试使用PriorityQueue来使其成为...

Store the Object as both key and value in HashMap. I am assuming that you are looking to retrieve object eventually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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