[Leetcode][Python]56: Merge Intervals

來源:互聯網
上載者:User

標籤:

# -*- coding: utf8 -*-
‘‘‘
__author__ = ‘[email protected]‘

56: Merge Intervals
https://oj.leetcode.com/problems/merge-intervals/

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].

===Comments by Dabay===
這道題想起來比較簡單,實現的時候惱火。
技巧在與,不是一個個地插入到已有的序列,而是把已有的序列插入到一個標杆Interval前面、交叉、後面。

對於每一個序列中的Interval,
- 如果它的end比標杆的start小,插入到前面
- 如果它的start比標杆的end大,插入到後面
- 如果它和標杆有交集,更新標杆的start和end
‘‘‘
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e

class Solution:
# @param intervals, a list of Interval
# @return a list of Interval
def merge(self, intervals):
def insert(interval, merged):
new_merged = []
i = 0
s = interval.start
e = interval.end
while i < len(merged):
if merged[i].end < s:
new_merged.append(merged[i])
i = i + 1
continue
if e < merged[i].start:
new_merged = new_merged + [Interval(s, e)] + merged[i:]
break
s = min(s, merged[i].start)
e = max(e, merged[i].end)
i = i + 1
else:
new_merged.append(Interval(s, e))
return new_merged


if len(intervals) <= 1:
return intervals

merged = [intervals[0]]
i = 1
while i < len(intervals):
merged = insert(intervals[i], merged)
i = i + 1

return merged


def main():
sol = Solution()
i1 = Interval(2,3)
i2 = Interval(4,5)
i3 = Interval(2,2)
i4 = Interval(15,18)
intervals = [i1,i2,i3,i4]
intervals = sol.merge(intervals)
for interval in intervals:
print "[%s, %s] " % (interval.start, interval.end),
print


if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)


[Leetcode][Python]56: Merge Intervals

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.