📜  使范围不重叠所需的最小移除量

📅  最后修改于: 2021-06-26 11:33:09             🧑  作者: Mango

给定具有起始值和结束值的范围列表,任务是找到需要删除的最小范围数,以使其余范围不重叠。

例子:

方法:

  • 按范围的起始值对范围进行排序。
  • 遍历范围并检查是否有任何范围的起点小于上一个范围的终点(即存在重叠)。
  • 删除终点更大的范围。

    下面的代码是上述方法的实现:

    C++
    #include 
    using namespace std;
      
    int minRemovals(vector >& ranges)
    {
      
        int size = ranges.size(), rem = 0;
      
        if (size <= 1)
            return 0;
      
        // Sort by minimum starting point
        sort(ranges.begin(), ranges.end(), 
            [](const vector& a, const vector& b) 
                        { return a[0] < b[0]; });
      
        int end = ranges[0][1];
        for (int i = 1; i < ranges.size(); i++) {
      
            // If the current starting point is less than
            // the previous interval's ending point 
            // (ie. there is an overlap)
            if (ranges[i][0] < end) {
                // increase rem
                rem++;
                // Remove the interval
                // with the higher ending point
                end = min(ranges[i][1], end);
            }
            else
                end = ranges[i][1];
        }
      
        return rem;
    }
      
    // Driver code
    int main()
    {
        vector > input = { { 19, 25 }, 
                            { 10, 20 }, { 16, 20 } };
        cout << minRemovals(input) << endl;
    }


    Python3
    def minRemovels (ranges):
      
        size = len(ranges)
        rem = 0
      
        # Sort by minimum starting point
        ranges.sort()
      
        end = ranges[0][1]
        for i in range(1, size):
      
            # If the current starting point is less
            # than the previous interval's ending
            # point (ie. there is an overlap)
            if (ranges[i][0] < end):
      
                # Increase rem
                rem += 1
      
                # Remove the interval
                # with the higher ending point
                end = min(ranges[i][1], end)
                  
            else:
                end = ranges[i][1]
      
        return rem
      
    # Driver Code
    if __name__ == '__main__':
          
        Input = [ [ 19, 25 ],
                  [ 10, 20 ],
                  [ 16, 20 ] ]
                    
        print(minRemovels(Input))
      
    # This code is contributed by himanshu77


    输出:
    2
    

    时间复杂度: O(n log n)

    如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。