跳到主要内容

最常用的数据结构

定长数组

arr = [0] * 10

动态数组

l = []
# Add a new element at tail
l.append(1)

双向链表

// LinkedList is actually a doubly-linked list, to mimic singly linked list, always operate at head
LinkedList<Integer> l = new LinkedList<>();
// insert at head, time complexity O(1)
l.offerFirst(7)
// access head, time complexity O(1)
l.peekFirst()
// remove head, time complexity O(1)
l.pollFirst()

# To mimic stack, always operate at tail
s = deque()
s.append(7)
s[-1]
s.pop()

队列

# To mimic a FIFO queue, push at tail, pop at head
q = deque()
q.append(7)
q[0]
q.popleft()
len(q) == 0

双端队列

q = deque()
# insert at tail, time complexity O(1)
q.push(7)
# access tail, time complexity O(1)
q[-1]
# remove tail, time complexity O(1)
q.pop()
# insert at head, time complexity O(1)
q.pushleft(7)
# access head, time complexity O(1)
q[0]
# remove head, time complexity O(1)
q.popleft()

优先队列(堆)

# min heap by default
pq = []
heapq.heappush(pq, 7)
pq[0]
heapq.heappop(pq)
len(pq) == 0

HashMap

m = {}

HashSet

s = set()