美文网首页
区间合并算法

区间合并算法

作者: madao756 | 来源:发表于2020-05-15 12:02 被阅读0次

    0X00 区间合并

    803. 区间合并

    from sys import stdin
    
    def read():
      return list(map(int, stdin.readline().split()))
      
    n = read()[0]
    segs = [None] * n
    
    for i in range(n):
      x, y = read()
      segs[i] = [x, y]
    
    segs.sort()
    res = []
    
    st, ed = float("-inf"), float("-inf")
    for x, y in segs:
      if ed < x:
        if st != float("-inf"): res.append([st, ed])
        st, ed = x, y
      else:
        ed = max(ed, y)
    if st != float("-inf"):
      res.append([st, ed])
    
    print(len(res))
    

    57. 插入区间

    import bisect
    class Solution:
        def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
            bisect.insort(intervals, newInterval)
            st, ed = float("-inf"), float("-inf")
            res = []
            for x, y in intervals:
                if ed < x:
                    if st != float("-inf"): res.append([st, ed])
                    st, ed = x, y
                else:
                    ed = max(ed, y)
            if st != float("-inf"): res.append([st, ed])
    
            return res
    

    相关文章

      网友评论

          本文标题:区间合并算法

          本文链接:https://www.haomeiwen.com/subject/oafcohtx.html