1. 程式人生 > >Learning python by leetcode: No.56 Merge intervals

Learning python by leetcode: No.56 Merge intervals

Contents

Preview

題目及演算法描述
Time complexity : O(nlgn).

code

# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    def
merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key = lambda interval:interval.start) merged_intervals = [] for interval in intervals : if not merged_intervals or merged_intervals[
-1].end < interval.start: merged_intervals.append(interval) else: merged_intervals[-1].end= max(merged_intervals[-1].end, interval.end) return merged_intervals

Details

list.sort()

list.sort() is a built-in function, sorting the list in place.
sort(*, key=None, reverse=False)

定義命名的關鍵字引數在沒有可變引數的情況下不要忘了寫分隔符*,否則定義的將是位置引數。

key specifies a function of one argument that is used to extract a comparison key from each list element .

i.e.: 不是用list中的元素來排序,而是各自派個代表出來火拼, 這個代表怎麼選拔呢? 就按照你指定給key的函式名, (python 是函數語言程式設計, 類似functor or function pointer)

list.sort() is stable.

this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

sorted

list.sort() has no return, if you want to get a new list, please use built-in function sorted()
sorted(iterable, *, key=None, reverse=False)
Return a new sorted list from the items in iterable.
sorted() is also stable.