GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/array/merge_intervals.py at master · vspriya05/algorithms Expand file tree/ Copy pathmerge_intervals.pyMore file actions 40 lines (35 loc) · 968 Bytes / Copy pathmerge_intervals.pyFile metadata and controls40 lines (35 loc) · 968 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 """ Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. """ # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def merge(intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, return out def print_intervals(intervals): res = [] for i in intervals: res.append('['+str(i.start)+','+str(i.end)+']') print("".join(res)) if __name__ == "__main__": given = [[1,3],[2,6],[8,10],[15,18]] intervals = [] for l, r in given: intervals.append(Interval(l,r)) print_intervals(intervals) print_intervals(merge(intervals)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |