Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

median - how to design a data structure that getMedian and insert in O(1)?

I thought about doing this in sort array and save the index of the median and its takes O(1). but I couldn't think about any way to do the insert in O(1) and keep the array sorted. I really appreciate it if someone can help me with this problem

question from:https://stackoverflow.com/questions/65874480/how-to-design-a-data-structure-that-getmedian-and-insert-in-o1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are asking for is impossible, because it would allow comparison-based sorting in O(n) time:

  • Suppose you have an unsorted array of length n.
  • Find the minimum element and maximum element in O(n) time.
  • Insert all n elements into the data structure, each insertion takes O(1) time so this takes O(n) time.
  • Insert n-1 extra copies of the minimum element. This also takes O(n) time.
  • Initialise an output array of length n.
  • Do this n times:
    • Read off the median of the elements currently in the data structure, and write it at the next position into the output array. This takes O(1) time.
    • Insert two copies of the maximum element into the data structure. This takes O(1) time.

The above algorithm supposedly runs in O(n) time, and the result is a sorted array of the elements from the input array. But this is impossible, because comparison-sorting takes Ω(n log n) time. Therefore, the supposed data structure cannot exist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...