查找每个给定 N 个区间右侧最近的非重叠区间的索引
给定一个包含N个区间的数组arr[] ,任务是计算与当前区间不重叠的每个给定N个区间右侧最近区间的索引。
例子:
Input: arr[] = {{3, 4}, {2, 3}, {1, 2}}
Output: -1 0 1
Explanation: For the interval arr[0], there exists no interval to the right of it. For interval arr[1], i.e, [2, 3], the interval [3, 4] is the closest interval to its right that does not overlap it. Hence the required answer for arr[1] is 0. For the interval arr[2], both arr[1] and arr[2] are on its right side and does not overlap with arr[2], but arr[1] is the closest among them.
Input: arr[] = {{1, 4}, {3, 4}, {2, 3}}
Output: -1 -1 1
方法:给定的问题可以在二分搜索的帮助下使用贪心方法来解决。这个想法是按照起始点的递增顺序对区间进行排序,并为每个区间找到最接近右侧的区间。以下是要遵循的步骤:
- 创建一个向量对V ,将起点和每个区间的索引存储在arr[]中。
- 按起始点的升序对向量V进行排序。
- 遍历数组arr[]并为每个索引找到最右边的区间的索引,这样它就不会与使用下界函数的当前区间重叠。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to find the index of closest
// non overlapping interval to the right
// of each of the given N intervals
vector closestInterval(
vector > arr,
int N)
{
// Vector to store starting value,
// index pair of arr[]
vector > V;
// Loop to iterate arr[]
for (int i = 0; i < N; i++) {
V.push_back({ arr[i].first, i });
}
// Sort the vector V
sort(V.begin(), V.end());
// Stores the resultant vector
vector res(N, -1);
// Loop to iterate arr[]
for (int i = 0; i < N; i++) {
// Calculate the closest
// interval to the right
auto it = lower_bound(
V.begin(), V.end(),
make_pair(arr[i].second, 0));
// If a valid interval
// exist update res
if (it != V.end()) {
int idx = it - V.begin();
// Update res
res[i] = V[idx].second;
}
}
// Return Answer
return res;
}
// Driver Code
int main()
{
vector > arr{ { 1, 4 },
{ 3, 4 },
{ 2, 3 } };
for (auto x : closestInterval(arr, arr.size())) {
cout << x << " ";
}
return 0;
}
Python3
# python3 program of the above approach
import bisect
# Function to find the index of closest
# non overlapping interval to the right
# of each of the given N intervals
def closestInterval(arr, N):
# Vector to store starting value,
# index pair of arr[]
V = []
# Loop to iterate arr[]
for i in range(0, N):
V.append([arr[i][0], i])
# Sort the vector V
V.sort()
# Stores the resultant vector
res = [-1 for _ in range(N)]
# Loop to iterate arr[]
for i in range(0, N):
# Calculate the closest
# interval to the right
it = bisect.bisect_left(V, [arr[i][1], 0])
# If a valid interval
# exist update res
if (it != len(V)):
idx = it
# Update res
res[i] = V[idx][1]
# Return Answer
return res
# Driver Code
if __name__ == "__main__":
arr = [[1, 4],
[3, 4],
[2, 3]]
for x in closestInterval(arr, len(arr)):
print(x, end=" ")
# This code is contributed by rakeshsahni
-1 -1 1
时间复杂度: O(N*log N)
辅助空间: O(1)