Leetcode - Data Structure


Tree

Insights

  1. When search on level order, bfs is better than dfs

Graph

Define a graph

use self-defined class GNode to define the node, use defaultdict to save all edges

class GNode(object):
    def __init__(self):
        self.inDegree = 0
        self.outNode = []
Class Solution(object):
	def findOrder(self, numCourses, prerequisites):
		from collections import defaultdict, deque
        graph = defaultdict(GNode)

Topological Sort

Main idea
sort in the number of in-degree

Algorithm

  1. use dictionary to store the information on all edges: {key: inNode, value: {inDegree, outNode}}
  2. use deque to store the node with inDegree == 0
  3. Use bfs to explore all nodes in the order of number of inDegree. For each node N in deque, we delete all edges connected with N and minus the inDegree of the nodes from N. If there is new node becomes inDegree == 0, add it into deque.

Time Complexity
O(V+E)

Leetcode example: 210. Course Schedule II
More in details

class GNode(object):
    def __init__(self):
        self.inDegree = 0
        self.outNode = []

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """

        from collections import defaultdict, deque
        graph = defaultdict(GNode)
        courseOrder = []

        for prerequisite in prerequisites:
            nextCourse, prevCourse = prerequisite[0], prerequisite[1]
            graph[prevCourse].outNode.append(nextCourse)
            graph[nextCourse].inDegree += 1
        totalEdges = len(prerequisites)

        nodepCourses = deque()
        for course in range(numCourses):
            if graph[course].inDegree == 0:
                nodepCourses.append(course)
        
        removedEdges = 0
        while nodepCourses:
            course = nodepCourses.popleft()
            courseOrder.append(course)
            for node in graph[course].outNode:
                graph[node].inDegree -= 1
                removedEdges += 1
                if graph[node].inDegree == 0:
                    nodepCourses.append(node)
        
        if totalEdges == removedEdges:
            return courseOrder
        return []

Shortest Path

Minimum Generate Tree


Hash Table


LinkedList

Tricks
We can add an additional node before the head or after the tail to simplify the processing.


DoubleLinkedList

Leetcode 146. LRU Cache


Heap (Priority-queue)

Functions

  • heappush(heap, [key, value])
  • key, value = heappop(heap)
heap = []
for value, num in valueMap.items():
	heappush(heap, [-num, value])
while heap:
	key, value = heappop(heap)

Tricks
The default order for heap is increasing. If we want to construct a decreasing heap, we can use -key.

Leetcode Examples

347. Top K Frequent Elements

Main idea
Heap sort

from collections import defaultdict
        valueMap = defaultdict(int)

        for num in nums:
            valueMap[num] += 1
        
        heap = []
        for value, num in valueMap.items():
            heappush(heap, [-num, value])
        
        i = 0
        answer = []
        while i < k:
            num, value = heappop(heap)
            answer.append(value)
            i += 1
        
        return answer

Binary


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值