热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

打印给定数组中重叠区间的一对索引

打印给定数组中重叠区间的一对索引原文:https://www.

打印给定数组中重叠区间的一对索引

原文:https://www . geeksforgeeks . org/print-一对来自给定数组的重叠区间索引/

给定一个大小为 N 的 2D 数组arr【】【】【】,每行代表表格 {X,Y} ( 基于 1 的索引)的区间,任务是找到一对重叠区间的索引。如果不存在这样的配对,则打印 -1 -1

示例:

输入: N = 5,arr[][] = {{1,5},{2,10},{3,10},{2,2},{2,15}}
输出: 4 1
解释:位置 4 即(2,2)的范围位于位置 1 即(1,5)的范围内。

输入: N = 4,arr[][] = {{2,10},{1,9},{1,8},{1,7}}
输出: -1 -1

天真的方法:最简单的方法是检查每对间隔中是否有一个位于另一个的内部。如果没有找到这样的间隔,打印 -1 -1 ,否则,打印找到的间隔的索引。
时间复杂度: O(N 2 )其中 N 为给定整数。
辅助空间: O(N)

有效方法:思路是根据每个区间的左边部分给定区间集合排序。按照以下步骤解决问题:


  1. 首先,通过存储每个区间的索引,按左边框对段进行递增排序。

  2. 然后,初始化变量 currcurrPos ,分别用排序数组中第一个区间的左边部分及其索引。

  3. 现在,遍历从 i = 0 到 N–1的排序的间隔。

  4. 如果任意两个相邻间隔的左边部分相等,那么打印它们的索引,因为其中一个位于另一个的内部。

  5. 如果当前区间的右边部分大于 curr ,则将 curr 设置为等于该右边部分,将 currPos 设置为等于原始数组中该区间的索引。否则,打印当前间隔的索引和存储在 currPos 变量中的索引。

  6. 遍历后,如果没有找到这样的间隔,打印 -1 -1

下面是上述方法的实现:

C++

// C++ program for the above approach
#include
using namespace std;
// Pair of two integers
// of the form {X, Y}
typedef pair ii;
// Pair of pairs and integers
typedef pair iii;
// FUnction to find a pair of indices of
// the overlapping interval in the array
ii segment_overlapping(int N,
                       vector > arr)
{
    // Store intervals {X, Y} along
    // with their indices
    vector tup;
    // Traverse the given intervals
    for (int i = 0; i         int x, y;
        x = arr[i][0];
        y = arr[i][1];
        // Store intervals and their indices
        tup.push_back(iii(ii(x, y), i + 1));
    }
    // Sort the intervals
    sort(tup.begin(), tup.end());
    // Stores Y of the first interval
    int curr = tup[0].first.second;
    // Stores index of first interval
    int currPos = tup[0].second;
    // Traverse the sorted intervals
    for (int i = 1; i         // Stores X value of previous interval
        int Q = tup[i - 1].first.first;
        // Stores X value of current interval
        int R = tup[i].first.first;
        // If Q and R equal
        if (Q == R) {
            // If Y value of immediate previous
            // interval is less than Y value of
            // current interval
            if (tup[i - 1].first.second
                                // Stores index of immediate
                // previous interval
                int X = tup[i - 1].second;
                // Stores index of current
                // interval
                int Y = tup[i].second;
                return { X, Y };
            }
            else {
                // Stores index of current
                // interval
                int X = tup[i].second;
                // Stores index of immediate
                // previous interval
                int Y = tup[i - 1].second;
                return { X, Y };
            }
        }
        // Stores Y value of current interval
        int T = tup[i].first.second;
        // T is less than or equal to curr
        if (T <= curr)
            return { tup[i].second, currPos };
        else {
            // Update curr
            curr = T;
            // Update currPos
            currPos = tup[i].second;
        }
    }
    // No answer exists
    return { -1, -1 };
}
// Driver Code
int main()
{
    // Given intervals
    vector > arr = { { 1, 5 }, { 2, 10 },
                                 { 3, 10 }, { 2, 2 },
                                 { 2, 15 } };
    // Size of intervals
    int N = arr.size();
    // Find answer
    ii ans = segment_overlapping(N, arr);
    // Print answer
    cout <}

Java 语言(一种计算机语言,尤用于创建网站)

// Java program for above approach
import java.util.*;
import java.lang.*;
// Pair of two integers
// of the form {X, Y}
class pair1
{
  int first, second;
  pair1(int first, int second)
  {
    this.first = first;
    this.secOnd= second;
  }
}
// Pair of pairs and integers
class pair2
{
  int first, second, index;
  pair2(int first, int second, int index)
  {
    this.first = first;
    this.secOnd= second;
    this.index = index;
  }
}
class GFG
{
  // Function to find a pair of indices of
  // the overlapping interval in the array
  static pair1 segment_overlapping(int N,
                                   int[][] arr)
  {
    // Store intervals {X, Y} along
    // with their indices
    ArrayList tup=new ArrayList<>();
    // Traverse the given intervals
    for (int i = 0; i     {
      int x, y;
      x = arr[i][0];
      y = arr[i][1];
      // Store intervals and their indices
      tup.add(new pair2(x, y, i + 1));
    }
    // Sort the intervals
    Collections.sort(tup, (a, b)->(a.first != b.first) ?
                     a.first - b.first:a.second - b.second);
    // Stores Y of the first interval
    int curr = tup.get(0).second;
    // Stores index of first interval
    int currPos = tup.get(0).index;
    // Traverse the sorted intervals
    for (int i = 1; i     {
      // Stores X value of previous interval
      int Q = tup.get(i - 1).first;
      // Stores X value of current interval
      int R = tup.get(i).first;
      // If Q and R equal
      if (Q == R)
      {
        // If Y value of immediate previous
        // interval is less than Y value of
        // current interval
        if (tup.get(i - 1).second
                    {
          // Stores index of immediate
          // previous interval
          int X = tup.get(i - 1).index;
          // Stores index of current
          // interval
          int Y = tup.get(i).index;
          return new pair1( X, Y );
        }
        else {
          // Stores index of current
          // interval
          int X = tup.get(i).index;
          // Stores index of immediate
          // previous interval
          int Y = tup.get(i - 1).index;
          return new pair1( X, Y );
        }
      }
      // Stores Y value of current interval
      int T = tup.get(i).second;
      // T is less than or equal to curr
      if (T <= curr)
        return new pair1( tup.get(i).index, currPos );
      else
      {
        // Update curr
        curr = T;
        // Update currPos
        currPos = tup.get(i).index;
      }
    }
    // No answer exists
    return new pair1(-1, -1 );
  }
  // Driver function
  public static void main (String[] args)
  {
    // Given intervals
    int[][] arr = { { 1, 5 }, { 2, 10 },
                   { 3, 10 }, { 2, 2 },
                   { 2, 15 } };
    // Size of intervals
    int N = arr.length;
    // Find answer
    pair1 ans = segment_overlapping(N, arr);
    // Print answer
    System.out.print(ans.first+" "+ans.second);
  }
}
// This code is contributed by offbeat

Python 3

# Python3 program for the above approach
# FUnction to find a pair of indices of
# the overlapping interval in the array
def segment_overlapping(N, arr):
    # Store intervals {X, Y} along
    # with their indices
    tup = []
    # Traverse the given intervals
    for i in range(N):
        x = arr[i][0]
        y = arr[i][1]
        # Store intervals and their indices
        tup.append([x, y, i + 1])
    # Sort the intervals
    tup = sorted(tup)
    # Stores Y of the first interval
    curr = tup[0][1]
    # Stores index of first interval
    currPos = tup[0][2]
    # Traverse the sorted intervals
    for i in range(1, N):
        # Stores X value of previous interval
        Q = tup[i - 1][0]
        # Stores X value of current interval
        R = tup[i][0]
        # If Q and R equal
        if (Q == R):
            # If Y value of immediate previous
            # interval is less than Y value of
            # current interval
            if (tup[i - 1][1]                 # Stores index of immediate
                # previous interval
                X = tup[i - 1][2]
                # Stores index of current
                # interval
                Y = tup[i][2]
                return [X, Y]
            else:
                # Stores index of current
                # interval
                X = tup[i][2]
                # Stores index of immediate
                # previous interval
                Y = tup[i - 1][2]
                return { X, Y }
        # Stores Y value of current interval
        T = tup[i][1]
        # T is less than or equal to curr
        if (T <= curr):
            return [tup[i][2], currPos]
        else:
            # Update curr
            curr = T
            # Update currPos
            currPos = tup[i][2]
    # No answer exists
    return [ -1, -1 ]
# Driver Code
if __name__ == '__main__':
    # Given intervals
    arr = [ [ 1, 5 ], [ 2, 10 ], [ 3, 10 ], [ 2, 2 ], [2, 15 ] ]
    # Size of intervals
    N = len(arr)
    # Find answer
    ans = segment_overlapping(N, arr)
    # Pranswer
    print(ans[0], ans[1])
    # This code is contributed by mohit kumar 29

C

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find a pair of indices of
// the overlapping interval in the array
static void segment_overlapping(int N, int[,] arr)
{
    // Store intervals {X, Y} along
    // with their indices
    List,
                     int>> tup = new List,
                                                      int>>();
    // Traverse the given intervals
    for(int i = 0; i     {
        int x, y;
        x = arr[i, 0];
        y = arr[i, 1];
        // Store intervals and their indices
        tup.Add(new Tuple, int>(
                      new Tuple(x, y), i + 1));
    }
    // Sort the intervals
    tup.Sort();
    // Stores Y of the first interval
    int curr = tup[0].Item1.Item2;
    // Stores index of first interval
    int currPos = tup[0].Item2;
    // Traverse the sorted intervals
    for(int i = 1; i     {
        // Stores X value of previous interval
        int Q = tup[i - 1].Item1.Item1;
        // Stores X value of current interval
        int R = tup[i].Item1.Item1;
        // If Q and R equal
        if (Q == R)
        {
            // If Y value of immediate previous
            // interval is less than Y value of
            // current interval
            if (tup[i - 1].Item1.Item2 <
                tup[i].Item1.Item2)
            {
                // Stores index of immediate
                // previous interval
                int X = tup[i - 1].Item2;
                // Stores index of current
                // interval
                int Y = tup[i].Item2;
                Console.WriteLine(X + " " + Y);
                return;
            }
            else
            {
                // Stores index of current
                // interval
                int X = tup[i].Item2;
                // Stores index of immediate
                // previous interval
                int Y = tup[i - 1].Item2;
                Console.WriteLine(X + " " + Y);
                return;
            }
        }
        // Stores Y value of current interval
        int T = tup[i].Item1.Item2;
        // T is less than or equal to curr
        if (T <= curr)
        {
            Console.Write(tup[i].Item2 + " " + currPos);
            return;
        }
        else
        {
            // Update curr
            curr = T;
            // Update currPos
            currPos = tup[i].Item2;
        }
    }
    // No answer exists
    Console.Write("-1 -1");
}
// Driver code
static public void Main()
{
    // Given intervals
    int[,] arr = { { 1, 5 }, { 2, 10 },
                   { 3, 10 }, { 2, 2 },
                   { 2, 15 } };
    // Size of intervals
    int N = arr.Length / 2;
    segment_overlapping(N, arr);
}
}
// This code is contributed by Dharanendra L V.

java 描述语言


Output: 

4 1

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


推荐阅读
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • importjava.util.ArrayList;publicclassPageIndex{privateintpageSize;每页要显示的行privateintpageNum ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
author-avatar
泉水叮咚139
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有