找到一个覆盖给定 N 个范围的所有元素的范围
给定包含 L 和 R 的 N 个范围。任务是检查或找到覆盖所有其他给定 N-1 范围的范围的索引(从 0 开始)。如果没有这样的范围,则打印 -1。
注意:所有 L 点和 R 点都是不同的。
例子:
Input: L[] = {1, 2}, R[] = {1, 2}
Output: -1
Input: L[] = {2, 4, 3, 1}, R[] = {4, 6, 7, 9}
Output: 3
Range at 3rd index i.e. 1 to 9 covers
all the elements of other N-1 ranges.
方法:由于所有L点和R点都是不同的,找到L点最小的范围和R点最大的范围,如果两者在同一个范围内,则表示所有其他范围都在其中,否则为不可能。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to check range
int findRange(int n, int lf[], int rt[])
{
// Index of smallest L and largest R
int mnlf = 0, mxrt = 0;
for (int i = 1; i < n; i++) {
if (lf[i] < lf[mnlf])
mnlf = i;
if (rt[i] > rt[mxrt])
mxrt = i;
}
// If the same range has smallest L
// and largest R
if (mnlf == mxrt)
return mnlf;
else
return -1;
}
// Driver Code
int main()
{
int N = 4;
int L[] = { 2, 4, 3, 1 };
int R[] = { 4, 6, 7, 9 };
cout << findRange(N, L, R);
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
class GFG {
// Function to check range
static int findRange(int n, int lf[], int rt[])
{
// Index of smallest L and largest R
int mnlf = 0, mxrt = 0;
for (int i = 1; i < n; i++) {
if (lf[i] < lf[mnlf])
mnlf = i;
if (rt[i] > rt[mxrt])
mxrt = i;
}
// If the same range has smallest L
// and largest R
if (mnlf == mxrt)
return mnlf;
else
return -1;
}
// Driver Code
public static void main (String[] args) {
int N = 4;
int[] L = { 2, 4, 3, 1 };
int []R = { 4, 6, 7, 9 };
System.out.println( findRange(N, L, R));
}
}
// This code is contributed by anuj_67..
Python3
# Python3 implementation of the
# above approach
# Function to check range
def findRange(n, lf, rt):
# Index of smallest L and
# largest R
mnlf, mxrt = 0, 0
for i in range(1, n):
if lf[i] < lf[mnlf]:
mnlf = i
if rt[i] > rt[mxrt]:
mxrt = i
# If the same range has smallest
# L and largest R
if mnlf == mxrt:
return mnlf
else:
return -1
# Driver Code
if __name__ == "__main__":
N = 4
L = [2, 4, 3, 1]
R = [4, 6, 7, 9]
print(findRange(N, L, R))
# This code is contributed
# by Rituraj Jain
C#
// C# implementation of the
// above approach
using System;
class GFG
{
// Function to check range
static int findRange(int n, int []lf,
int []rt)
{
// Index of smallest L and largest R
int mnlf = 0, mxrt = 0;
for (int i = 1; i < n; i++)
{
if (lf[i] < lf[mnlf])
mnlf = i;
if (rt[i] > rt[mxrt])
mxrt = i;
}
// If the same range has smallest L
// and largest R
if (mnlf == mxrt)
return mnlf;
else
return -1;
}
// Driver Code
public static void Main ()
{
int N = 4;
int[] L = { 2, 4, 3, 1 };
int []R = { 4, 6, 7, 9 };
Console.WriteLine(findRange(N, L, R));
}
}
// This code is contributed by anuj_67..
PHP
$rt[$mxrt])
$mxrt = $i;
}
// If the same range has smallest
// L and largest R
if ($mnlf == $mxrt)
return $mnlf;
else
return -1;
}
// Driver Code
$N = 4;
$L = array( 2, 4, 3, 1 );
$R = array( 4, 6, 7, 9 );
echo findRange($N, $L, $R);
// This code is contributed
// by inder_verma
?>
Javascript
输出:
3
时间复杂度: O(N)