首页 > 解决方案 > 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 ?

标签: algorithm

解决方案


  1. 找出最大的数。您遍历间隔并检查间隔的结束。在您的情况下,它是 9. Setk = 1L = 9
  2. 也许还有其他 9。将区间标记(7,9)为已访问并检查是否有任何其他区间包含 9 a >= 9 && b <= '。在您的情况下,只有一个 9。
  3. 减少当前最大数字 ( L -= L) 并清除访问间隔的历史记录。并重复检查间隔。
  4. 每次你在一个区间内遇到你当前的最大数字时,你应该增加k这个区间并将其标记为已访问。一旦它等于kth当前的最大数字L就是你的答案。

推荐阅读