简体   繁体   中英

kth largest element in range interval

Given a list of overlapping intervals of integers. I need to find the kth largest element.

Example:

List { (3,4), (2,8), (4,8), (1,3), (7,9) }

This interval represents numbers as

[3, 4], [2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8], [1, 2, 3], and [7, 8, 9].

If we merge and sort it in decreasing order, we get

9, 8, 8, 8, 7, 7, 7, 6, 6, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 1

Now the 4th largest number in the list is 8.

Can anyone please explain an efficient (we don't have to generate the list) algorithm to find the kth element given only a list of internals ?

  1. Find out the largest number. You go through intervals and examine ends of intervals. In your case it is 9. Set k = 1 , and L = 9 .
  2. Perhaps there are other 9s. Mark (7,9) interval as visited and check if any other intervals contains 9 a >= 9 && b <= ' . In your case there is only one 9.
  3. Decrement current largest number ( L -= L ) and clear history of visited intervals. And repeat checking intervals.
  4. Every time you meet your current largest number within an interval you should increment k and mark the interval as visited. As soon as it becomes equal to kth the current greatest number L is your answer.

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