Python Sort
Sort with diff data structure
List
Time complexity: O(NlogN)
One-dimension List
a = [3,2,1,4]
a.sort()
multi-dimension List: use “key”
intervals = [[1,4],[0,4]]
intervals = sorted(intervals, key = lambda x: x[0])
# Output: [[0,4], [1,4]]
- “sorted” can not modify the original list, we need to assign the result to a list.
- Example: Leedcode #56. Merge Intervals
intervals = [[1,4],[0,4],[1,5]]
intervals = sorted(intervals, key = lambda x: (x[0], x[1]), reverse = True)
# Output: [[1,5],[1,4],[0,4]]
- Use two keys to sort, we need use “()” to include all keys
Heapq
- heapq.heappush(heap, item)
Time complexity: O(logN)
Push the value item onto the heap, maintaining the heap invariant. - heapq.heappop(heap)
Time complexity: O(logN)
Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].
Heapsort
def heapsort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]