简体   繁体   中英

Data structure for the minimum value and its offset in a mutating array

I have an int array[4096] . I want to always know the minimum value and its offset in this array, without having to ever search through it.

Obviously, on setting an element to a new value, it can be compared with the minimum and replace it if applicable. However, if setting the offset that's currently the minimum, and making it no longer the minimum, it gets more difficult.

How can this be done, as efficiently as possible?

You can use a priority queue supporting deletion and decrease-key to support this. Whenever a value changes, if the value decreased, then call decrease-key on it to decrease its value in the priority queue. If the value increased, delete the value and then reinsert it into the priority queue.

Assuming the priority queue is backed by a structure that efficiently supports these operations (typically, binary heaps with appropriate bookkeeping can do this in O(log n) time each), then you can support this much faster than just doing a linear scan over the elements each time. If you don't have a binary heap like this lying around, you can always use a tree-backed map (keys are values, elements are positions in the array) to do this.

Hope this helps!

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