📌  相关文章
📜  从给定的一组间隔中找到最少的非重叠数

📅  最后修改于: 2021-09-03 03:12:57             🧑  作者: Mango

给定一个由整数对组成的数组区间,表示大小为N的区间的起点和终点。任务是从给定的一组区间中找到最小的非负整数,它是一个非重叠数。
输入约束:

1 \le N \le 10^{5}0 \le interval[i] \le 10^{9}

例子:

天真的方法:

  • 创建一个大小为MAX的访问数组,并为每个间隔标记从开始结束的所有值。
  • 最后,从1MAX迭代,找到未被访问过的最小值。

但是,如果区间坐标高达 10 9 ,则此方法将不起作用。

时间复杂度: O (N 2 )
辅助空间: O (MAX)

有效的方法:

  1. 而不是从头到尾迭代,只需创建一个访问过的数组,并为每个范围标记vis[start] = 1vis[end+1] = -1
  2. 取数组的前缀和。
  3. 然后遍历数组以找到第一个值为0 的整数。

下面是上述方法的实现:

C++
// C++ program to find the
// least non-overlapping number
// from a given set intervals
 
#include 
using namespace std;
const int MAX = 1e5 + 5;
 
// function to find the smallest
// non-overlapping number
void find_missing(
    vector > interval)
{
    // create a visited array
    vector vis(MAX);
 
    for (int i = 0; i < interval.size(); ++i) {
        int start = interval[i].first;
        int end = interval[i].second;
        vis[start]++;
        vis[end + 1]--;
    }
 
    // find the first missing value
    for (int i = 1; i < MAX; i++) {
        vis[i] += vis[i - 1];
        if (!vis[i]) {
            cout << i << endl;
            return;
        }
    }
}
// Driver function
int main()
{
 
    vector > interval
        = { { 0, 14 }, { 86, 108 },
            { 22, 30 }, { 5, 17 } };
    find_missing(interval);
    return 0;
}


Java
// Java program to find the
// least non-overlapping number
// from a given set intervals
class GFG{
   
static int MAX = (int) (1e5 + 5);
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
// function to find the smallest
// non-overlapping number
static void find_missing(
    pair[] interval)
{
    // create a visited array
    int [] vis = new int[MAX];
 
    for (int i = 0; i < interval.length; ++i)
    {
        int start = interval[i].first;
        int end = interval[i].second;
        vis[start]++;
        vis[end + 1]--;
    }
 
    // find the first missing value
    for (int i = 1; i < MAX; i++) {
        vis[i] += vis[i - 1];
        if (vis[i]==0) {
            System.out.print(i +"\n");
            return;
        }
    }
}
// Driver function
public static void main(String[] args)
{
 
    pair []interval = {new pair( 0, 14 ),
                       new pair( 86, 108 ),
                       new pair( 22, 30 ),
                       new pair( 5, 17 )};
    find_missing(interval);
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program to find the
# least non-overlapping number
# from a given set intervals
MAX = int(1e5 + 5)
 
# Function to find the smallest
# non-overlapping number
def find_missing(interval):
     
    # Create a visited array
    vis = [0] * (MAX)
 
    for i in range(len(interval)):
        start = interval[i][0]
        end = interval[i][1]
        vis[start] += 1
        vis[end + 1] -= 1
 
    # Find the first missing value
    for i in range(1, MAX):
        vis[i] += vis[i - 1]
         
        if (vis[i] == 0):
            print(i)
            return
 
# Driver code
interval = [ [ 0, 14 ], [ 86, 108 ],
             [ 22, 30 ], [ 5, 17 ] ]
              
find_missing(interval)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to find the
// least non-overlapping number
// from a given set intervals
using System;
 
class GFG{
 
static int MAX = (int)(1e5 + 5);
class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to find the smallest
// non-overlapping number
static void find_missing(pair[] interval)
{
     
    // Create a visited array
    int [] vis = new int[MAX];
 
    for(int i = 0; i < interval.Length; ++i)
    {
        int start = interval[i].first;
        int end = interval[i].second;
         
        vis[start]++;
        vis[end + 1]--;
    }
 
    // Find the first missing value
    for(int i = 1; i < MAX; i++)
    {
        vis[i] += vis[i - 1];
        if (vis[i] == 0)
        {
            Console.Write(i + "\n");
            return;
        }
    }
}
 
// Driver code
public static void Main(String[] args)
{
    pair []interval = { new pair(0, 14),
                        new pair(86, 108),
                        new pair(22, 30),
                        new pair(5, 17) };
                         
    find_missing(interval);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program to find the
// least non-overlapping number
// from a given set intervals
 
#include 
using namespace std;
 
// function to find the smallest
// non-overlapping number
void find_missing(
    vector > interval)
{
    // Sort the intervals based on their
    // starting value
    sort(interval.begin(), interval.end());
 
    int mx = 0;
 
    for (int i = 0; i < (int)interval.size(); ++i) {
 
        // check if any missing vaue exist
        if (interval[i].first > mx) {
            cout << mx;
            return;
        }
 
        else
            mx = max(mx, interval[i].second + 1);
    }
    // finally print the missing value
    cout << mx;
}
// Driver function
int main()
{
 
    vector > interval
        = { { 0, 14 }, { 86, 108 },
            { 22, 30 }, { 5, 17 } };
    find_missing(interval);
    return 0;
}


Java
// Java program to find the
// least non-overlapping number
// from a given set intervals
import java.util.*;
import java.io.*;
 
class GFG{
     
static class Pair implements Comparable
{
    int start,end;
    Pair(int s, int e)
    {
        start = s;
        end = e;
    }
     
    public int compareTo(Pair p)
    {
        return this.start - p.start;
    }
}
 
// Function to find the smallest
// non-overlapping number
static void findMissing(ArrayList interval)
{
     
    // Sort the intervals based on their
    // starting value
    Collections.sort(interval);
 
    int mx = 0;
 
    for(int i = 0; i < interval.size(); ++i)
    {
         
        // Check if any missing vaue exist
        if (interval.get(i).start > mx)
        {
            System.out.println(mx);
            return;
        }
        else
            mx = Math.max(mx, interval.get(i).end + 1);
    }
     
    // Finally print the missing value
    System.out.println(mx);
}
 
// Driver code
public static void main(String []args)
{
    ArrayList interval = new ArrayList<>();
    interval.add(new Pair(0, 14));
    interval.add(new Pair(86, 108));
    interval.add(new Pair(22, 30));
    interval.add(new Pair(5, 17));
     
    findMissing(interval);
}
}
 
// This code is contributed by Ganeshchowdharysadanala


Python3
# Python3 program to find the
# least non-overlapping number
# from a given set intervals
 
# function to find the smallest
# non-overlapping number
def find_missing(interval):
 
    # Sort the intervals based 
    # on their starting value
    interval.sort()
 
    mx = 0
 
    for i in range (len(interval)):
 
        # Check if any missing
        # vaue exist
        if (interval[i][0] > mx):
            print (mx)
            return
        
        else:
            mx = max(mx,
                     interval[i][1] + 1)
 
    # Finally print the missing value
    print (mx)
 
# Driver code
if __name__ == "__main__":
 
    interval = [[0, 14], [86, 108],
                [22, 30], [5, 17]]
    find_missing(interval);
    
# This code is contributed by Chitranayal


C#
// C# program to find the
// least non-overlapping number
// from a given set intervals
using System;
using System.Collections.Generic;
class GFG{
     
class Pair : IComparable
{
    public int start,end;
    public Pair(int s, int e)
    {
        start = s;
        end = e;
    }
     
    public int CompareTo(Pair p)
    {
        return this.start - p.start;
    }
}
 
// Function to find the smallest
// non-overlapping number
static void findMissing(List interval)
{
     
    // Sort the intervals based on their
    // starting value
    interval.Sort();
    int mx = 0;
    for(int i = 0; i < interval.Count; ++i)
    {
         
        // Check if any missing vaue exist
        if (interval[i].start > mx)
        {
            Console.WriteLine(mx);
            return;
        }
        else
            mx = Math.Max(mx, interval[i].end + 1);
    }
     
    // Finally print the missing value
    Console.WriteLine(mx);
}
 
// Driver code
public static void Main(String []args)
{
    List interval = new List();
    interval.Add(new Pair(0, 14));
    interval.Add(new Pair(86, 108));
    interval.Add(new Pair(22, 30));
    interval.Add(new Pair(5, 17));
     
    findMissing(interval);
}
}
 
// This code is contributed by shikhasingrajput


输出:
18

时间复杂度: O (N)
辅助空间: O (MAX)
但是,如果区间坐标达到 10 9 ,这种方法也将不起作用。

有效的方法:

  1. 按开始坐标和每个下一个范围对范围进行排序。
  2. 检查起点是否大于目前遇到的最大结束坐标,然后可以找到一个缺失的数字,它将是previous_max + 1

下面是上述方法的实现:

C++

// C++ program to find the
// least non-overlapping number
// from a given set intervals
 
#include 
using namespace std;
 
// function to find the smallest
// non-overlapping number
void find_missing(
    vector > interval)
{
    // Sort the intervals based on their
    // starting value
    sort(interval.begin(), interval.end());
 
    int mx = 0;
 
    for (int i = 0; i < (int)interval.size(); ++i) {
 
        // check if any missing vaue exist
        if (interval[i].first > mx) {
            cout << mx;
            return;
        }
 
        else
            mx = max(mx, interval[i].second + 1);
    }
    // finally print the missing value
    cout << mx;
}
// Driver function
int main()
{
 
    vector > interval
        = { { 0, 14 }, { 86, 108 },
            { 22, 30 }, { 5, 17 } };
    find_missing(interval);
    return 0;
}

Java

// Java program to find the
// least non-overlapping number
// from a given set intervals
import java.util.*;
import java.io.*;
 
class GFG{
     
static class Pair implements Comparable
{
    int start,end;
    Pair(int s, int e)
    {
        start = s;
        end = e;
    }
     
    public int compareTo(Pair p)
    {
        return this.start - p.start;
    }
}
 
// Function to find the smallest
// non-overlapping number
static void findMissing(ArrayList interval)
{
     
    // Sort the intervals based on their
    // starting value
    Collections.sort(interval);
 
    int mx = 0;
 
    for(int i = 0; i < interval.size(); ++i)
    {
         
        // Check if any missing vaue exist
        if (interval.get(i).start > mx)
        {
            System.out.println(mx);
            return;
        }
        else
            mx = Math.max(mx, interval.get(i).end + 1);
    }
     
    // Finally print the missing value
    System.out.println(mx);
}
 
// Driver code
public static void main(String []args)
{
    ArrayList interval = new ArrayList<>();
    interval.add(new Pair(0, 14));
    interval.add(new Pair(86, 108));
    interval.add(new Pair(22, 30));
    interval.add(new Pair(5, 17));
     
    findMissing(interval);
}
}
 
// This code is contributed by Ganeshchowdharysadanala

蟒蛇3

# Python3 program to find the
# least non-overlapping number
# from a given set intervals
 
# function to find the smallest
# non-overlapping number
def find_missing(interval):
 
    # Sort the intervals based 
    # on their starting value
    interval.sort()
 
    mx = 0
 
    for i in range (len(interval)):
 
        # Check if any missing
        # vaue exist
        if (interval[i][0] > mx):
            print (mx)
            return
        
        else:
            mx = max(mx,
                     interval[i][1] + 1)
 
    # Finally print the missing value
    print (mx)
 
# Driver code
if __name__ == "__main__":
 
    interval = [[0, 14], [86, 108],
                [22, 30], [5, 17]]
    find_missing(interval);
    
# This code is contributed by Chitranayal

C#

// C# program to find the
// least non-overlapping number
// from a given set intervals
using System;
using System.Collections.Generic;
class GFG{
     
class Pair : IComparable
{
    public int start,end;
    public Pair(int s, int e)
    {
        start = s;
        end = e;
    }
     
    public int CompareTo(Pair p)
    {
        return this.start - p.start;
    }
}
 
// Function to find the smallest
// non-overlapping number
static void findMissing(List interval)
{
     
    // Sort the intervals based on their
    // starting value
    interval.Sort();
    int mx = 0;
    for(int i = 0; i < interval.Count; ++i)
    {
         
        // Check if any missing vaue exist
        if (interval[i].start > mx)
        {
            Console.WriteLine(mx);
            return;
        }
        else
            mx = Math.Max(mx, interval[i].end + 1);
    }
     
    // Finally print the missing value
    Console.WriteLine(mx);
}
 
// Driver code
public static void Main(String []args)
{
    List interval = new List();
    interval.Add(new Pair(0, 14));
    interval.Add(new Pair(86, 108));
    interval.Add(new Pair(22, 30));
    interval.Add(new Pair(5, 17));
     
    findMissing(interval);
}
}
 
// This code is contributed by shikhasingrajput

输出:

18

时间复杂度: O (N * logN)
辅助空间: O (1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live