Chapter 4 Data structure algorithm

py built-in data structure algorithms often test

Commonly used algorithms and data structures built

sorted
list/set/dict/tuple

Built-in data structures and algorithms used

Data structure / algorithm Built-in language Built-in library
Linear structure list (list) / tuple (tuple) array (array, not used) /collections.namedtuple
Chain structure collections.deque (deque)
Dictionary structure dict (collection) collections.Counte (counter) / OrderedDict (ordered dictionary)
Collection structure set (collection) / frozenset (immutable collection)
Sorting Algorithm sorted
Binary arithmetic bisect module
Heap algorithm heapq module
Caching algorithms functools.lru_cached(Least Recent Used, py3)

I have used the collections module it?
collections module provides some built-in data structures extended
namedtuple
the deque
Counter
OrderedDict
a defaultdict

import collections

Point = collections.namedtuple('Point', 'x, y')

p = Point(1, 2)
print(p.x)
print(p.y)
print(p[0])
print(p[1])
#namedtuple让tuple属性可读

#deque可以方便地实现queue/stack
de = collections.deque()
de.append(1)
de.appendleft(0)
deque([0, 1])
de.pop()
de.popleft()
import collections

c = collections.Counter()
c = collections.Counter('abcab')

print(c)
print(c['a'])
print(c.most_common())
#需要计数器的地方使用Counter  

# !< out:
    Counter({'a': 2, 'b': 2, 'c': 1})
    2
    [('a', 2), ('b', 2), ('c', 1)]
import collections

od = collections.OrderedDict()

od['c'] = 'c'
od['a'] = 'a'
od['b'] = 'b'

print(list(od.keys()))
# !< out:
    ['c', 'a', 'b']
#LRU cache
#带有默认值的字典
import collections
dd = collections.defaultdict(int)

print(dd['a'])
dd['b'] += 1

print(dd)
# !< out:
    0
    defaultdict(<class 'int'>, {'a': 0, 'b': 1})

The underlying principle to achieve
py dict the underlying structure

  • dict the underlying hash table used
    to support the Quick Find Use hash table as the underlying structure of
    the hash table, the average search time complexity of O (1)
    CPython interpreter uses a hash second exploratory resolve conflicts

Hash collision and expansion are often questions

py list / tuple difference

list vs tuple
is linear index structure supports access
list is a mutable object, tuple stored immutable reference
list not as the key dictionary, tuple can (not mutable object hash)

t = ([1], 2, 3)
t[0].append(1)

#保存的引用不可变指的是你没法替换掉这个对象
#但是如果对本身是一个可变对象,是可以修改
#这个引用指向的可变对象的

What is LRUCache?
Least-Recently-Used to replace the objects the least recently used
caching strategies removed when the cache space is not enough of a need for a way to eliminate key
common with LRU, LFU and other
LRU queue continue to access the latest key cycle through the use of a double-ended placed header realization

How to achieve LRUCache?
Dictionary used to cache, double-ended loop access list is used to record the sequence
using the built-in dict + collections.OrderedDict py achieve

dict used as cache k / v key-value pairs

OrderedDict used to implement the updated recently visited key

from collections import OrderedDict

class LRUCache:
    
    def __init__(self, capacity=128):
        self.od = OrderedDict()
        self.capacity = capacity
    
    def get(self, key): #每次访问更新最新使用的key
        if key in self.od:
            val = self.od[key]
            self.od.move_to_end(key)
            return val
        else:
            return -1
        
    def put(self, key, value): #更新k/v
        if key in self.od:
            del self.od[key]
            self.od[key] = value #更新key到表头
        else: #insert
            self.od[key] = value
            #判断当前容量是否已经满了
            if len(self.od) > self.capacity:
                self.od.popitem(last=False)
                
    #请实现LRUCache并编写单元测试

Algorithms often test centers

+ Lookup priority ordering
often test sorting algorithms: bubble sort, quick sort, merge sort, heap sort
linear search, binary search, etc.
can be implemented independently of the code (hand) can analyze the time and space complexity
and space complexity of the sorting algorithm used

Sorting Algorithm Worst Time Analysis The average time complexity stability Space complexity
Bubble Sort O (n ^ 2) O (n ^ 2) stable O (1)
Selection Sort O (n ^ 2) O (n ^ 2) Unstable O (1)
Insertion Sort O (n ^ 2) O (n ^ 2) stable O (1)
Quick Sort O (n ^ 2) O(n*log2n) Unstable O (log2n) - O (n)
Heapsort O(n*log2n) O(n*log2n) Unstable O (1)

py regular exam data structure

Often exam type
py web often test the backend data structure
common data structure linked lists, queues, stacks, binary trees, heap
using the built-in structure for advanced data structures, such as the built-in list / deque realized stack

Common questions on Leetcode or <to prove safety offer>

Test often linked list data structure of the
list single chain, double chain, a double-ended circular linked list
how to represent Py list structure
linked list implementation common operations, such as insertion node, inverted list, merging a plurality of linked lists
Leetcode common practice title list

Linked list data structures

#leetcode
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre = None
        cur = head
        while cur:
            nextnode = cur.next
            cur.next = pre
            pre = cur
            cur = nextnode
        return pre

Often test queue data structure of the
queue (queue) is a FIFO structure of
how to use py queue?

Queue of apend and pop operation, how to do FIFO

Py using a list or queue collections.deque

Collections.deque deque

#实现队列, 使用deque
from collections import deque

class Queue:
    def __init__(self):
        self.items = deque()

    def append(self, val):
        return self.items.append(val)

    def pop(self):
        return self.items.popleft()

    def empty(self):
        return len(self.items) == 0

def test_queue():
    q = Queue()
    q.append(0)
    q.append(1)
    q.append(2)
    print(q.pop())
    print(q.pop())
    print(q.pop())

test_queue()

Often test stack data structure of the
stack is a LIFO structure of
how to achieve py stack?
Implemented stack push and pop operations, how to do LIFO
likewise be implemented using py list or stack collections.deque

#请实现一个Stack
#借助内置的数据结构非常容易实现一个栈Stack, 后进先出
from collections import deque
class Stack(object):
    def __init__(self):
        self.deque = deque()    #或者用list
    
    def push(self, value):
        self.deque.append(value)
    
    def pop(self):
        return self.deque.pop()
   
#如何使用两个stack 实现队列 先进先出
#实现获取最小值栈minstack

Often test the dictionary data structure and a set of
py dict / set the underlying hash table are the
realization of the principle of the hash table, the bottom is actually an array
quickly locate a hash function element, the average search O (1), very quickly
being added elements of the hash table can cause re-open space, copy elements to the new array before

Hash table conflict resolution
link method and open addressing method
after a collision of use of a key element list filled with the same key elements
OpenAddressed method is looking after the conflict according to an embodiment (second exploratory) available slot
cpython used a second look

Test often binary tree data structure of
the first order, in sequence, after traversing the
first (root) sequence: first treat roots, then the left subtree, then the right subtree
of (roots) sequence: first processing left subtree, then root, then the right subtree
. (root) sequence: first processing left subtree, then the right subtree, the root finally

#数据结构之二叉树:
#树的遍历方式
#先序遍历 递归代码里先处理根
class BinTreeNode(object):
    def __init__(self, data, left=None, right=None):
        self.data, self.left, self.right = data, left, right
        
class BinTree(object):
    def __init__(self, root=None):
        self.root = root
    
    def preorder_trav(self, subtree):
        """先(根)序遍历"""
        if subtree is not None:
            print(subtree.data) #递归函数里先处理根
            self.preorder_trav(subtree.left)    #递归处理左子树
            self.preorder_trav(subtree.right)   #递归处理右子树
     #中序遍历 调整下把print(subtree.data)放中间就好       
    def inorder_trav(self, subtree):
        if subtree is not None:
            self.preorder_trav(subtree.left)
            print(subtree.data) #中序遍历放到中间就好
            self.preorder_trav(subtree.right)

Often test heap data structure of the
heap is a complete binary tree in fact, there are maximum and minimum heap heap
max heap: than it is for big kids, the value of each non-leaf node V V of
the largest heap support each pop operation to obtain the largest element, The minimum heap get the smallest element

最大堆支持每次pop操作获取最大的元素, 最小堆获取最小元素

常见问题:用堆来完成topk问题, 从海量数字找寻找最大的k个
"""
class Topk:

    def __init__(self, iterable, k):
        self.minheap = []
        self.capacity = k
        self.iterable = iterable

    def push(self, val):
        if len(self.minheap) >= self.capacity:
            min_val = self.minheap[0]
            if val < min_val:   #可以直接>操作, 这里只显示跳过这个元素
                pass
            else:
                heapq.heapreplace(self.minheap, val) #返回并且pop堆顶最小值,
                                                     #推入新的val值并调整堆
        else:
            heapq.heappush(self.minheap, val)   #前面k个元素直接放入minheap

    def get_topk(self):
        for val in self.iterable:
            self.push(val)
        return self.minheap

def test():
    import random
    i = list(range(1000))   #这里可以是一个可迭代的元素, 节省内存
    random.shuffle(i)
    _ = Topk(i, 10)
    print(_.get_topk())

test()
# !< out:
[990, 991, 992, 995, 993, 998, 994, 996, 997, 999]

Heap solve the problem TOPK

py whiteboard programming (handwritten code)
handwriting algorithm question
brush title, Leetcode <prove safety offer> github solution to a problem
how to prepare
to brush the question
done before the system before finishing the interview questions, but do not rely on memory really understand and grasp
lay a solid foundation is the key, interview common problems can brush assault, feel saved

Before the interview practice
brush title (leetcode + wins the offer + surface after)
<wins the offer> py with a common topic on achieving
the common classification title on leetcode Brush (github search leetcode classification)
common sorting algorithms and data structures can be handwritten

Often test data structure that - the list
chain pointer operation involves more complex, error prone, often used as exam
familiar and common operations defined list of
regular exam: delete a list node leetcode 237
merging two sorted linked list leetcode 21

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        root = ListNode(None)
        cur = root
        while l1 and l2:
            if l1.val < l2.val:
                node = ListNode(l1.val)
                l1 = l1.next
            else:
                node = ListNode(l2.val)
                l2 = l2.next
            cur.next = node
            cur = node
        if l1 is None:
            cur.next = l2
        else:
            cur.next = l1
        return root.next

Binary
Binary Tree and pointer operations involving recursive, recursive visits often combined
binary operation involves a recursive operation and pointer
image binary tree (inverted binary)
how the binary tree traversal sequence (breadth-first) 102 issues
an output binary tree results about Perspective

class TreeNode:
    def __init__(self, val, left, right):
        self.val, self.left, self.right = val, left, right

#leetcode 237   

Stacks and queues

LIFO vs FIFO

Py with the master list or collections.deque () implement stacks and queues
regular exam: Stack queue (implemented using two stacks)
leetcode: Implement - Queue - the using - title Stacks 232

     |__|   |__|
     |__|   |__|
     |__|   |__|
     |__|   |__|
      S1     S2
栈2不为空直接pop 否则把栈1的所有元素放到栈2
然后执行栈2 pop操作

the deque () deque

from collections import deque

class Stack:
    def __init__(self):
        self.items = deque()

    def push(self, val):
        return self.items.append(val)

    def pop(self):
        return self.items.pop()

    def top(self): #return stack top value
        return self.items[-1]

    def empty(self):
        return len(self.items) == 0


class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.s1 = Stack()
        self.s2 = Stack()

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.s1.push(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if not self.s2.empty():
            return self.s2.pop()
        while not self.s1.empty():
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.s2.empty():
            return self.s2.top()
        while not self.s1.empty():
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.top()

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return self.s1.empty() and self.s2.empty()

def test():
    q = MyQueue()
    q.push(1)
    q.push(2)
    q.push(3)
    print(q.pop())
    print(q.pop())
    print(q.pop())

test()

Heap data structures

Heap often basic questions about the merger more orderly (array / list) Topk problem
| - understand the concept of heap heap is a complete binary tree has a maximum and minimum heap heap
| - py will use the built-in module for operation heapq heap
| - often questions: k ordered merge list leetcode merge-k-sorted-list 23 title
merging two sorted linked list ..

|. --1 read all the value chain

|. --2 constructed to achieve a minimum heap heapq

| --3 the minimum stack configuration list.

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

from heapq import heapify,heappop
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        h = []
        for node in lists:
            while node:
                h.append(node.val)
                node = node.next
        if not h:
            return None
        heapify(h)

        root = ListNode(heappop(h))
        curnode = root
        while h:
            nextnode = ListNode(heappop(h))
            curnode.next = nextnode
            curnode = nextnode
        return root

String constant questions

Title character string
information on common string operations
reversing a string 334
determines whether a string is a palindrome 9

Built-py string manipulation split, upper, replace etc

s.reverse()

def reverseString(self, s):
beg = 0
end = len(s) - 1
while beg < end:
    s[beg], s[end] = s[end], s[beg]
    beg += 1
    end -= 1
def isPalindrome(x):
    if x < 0:
        return False
    s = str(x)
    beg, end = 0, len(s) - 1
    while beg < end:
        if s[beg] == s[end]:
            beg += 1
            end -= 1
        else:
            return False
    return True

Double-ended strings traversal method, similar problems can be solved

Exercises
| - linked lists, strings,
how to reverse a singly-linked list
using a round-robin fashion to achieve
using a recursive manner

Guess you like

Origin www.cnblogs.com/xuzhaoping/p/11616745.html