算法模板汇总
算法模板汇总
1、牛顿迭代法(c++代码)
int mysqrt(int x){ double tmps = x; double k = 1.0; double k0 = 0.0; while(abs(k0-k) >= 1){ k0 = k; k = (k + tmpx/k)/2; } return (int)k; }
2、二分查找代码模板
left, right = 0, len(array) - 1 while left <= right: mid = (left + right) / 2 if array[mid] == target: #find the target!! break or return result elif array[mid] < target: left = mid + 1 else: right = mid + 1
3、递归代码模板
def recursion(level, param1, param2, ...): #recursion terminator if level > MAX_LEVEL: process_result return #process logic in current level process(level, data...) #drill down self.recursion(level + 1,p1, ...) #reverse the current level status if needed
4、分治代码模板
def divide_conquer(problem, param1, param2, ...): if problem is None: print_result return #prepare data data = prepare_data(problem) subproblems = split_problem(problem, data) #conquer subproblems subresult1 = self.divide_conquer(subproblems[0], p1, ...) subresult2 = self.divide_conquer(subproblems[1], p1, ...) subresult3 = self.divide_conquer(subproblems[2], p1, ...) #process and generate the final result result = process_result(subresult1, subresult2, subresult3, ...) #revert the current level states
5、Tire树代码模板
class Trie(object): def __init__(self): self.root = {} self.end_of_word = '#' def insert(self, word): node = self.root for char in word: node = node.setdefault(char, {}) node[self.end_of_word] = self.end_of_word def search(self, word): node = self.root for char in word: if char not in node: return False node = node[char] return self.end_of_word in node def startsWith(self, prefix): node = self.root for char in prefix: if char not in node: return False node = node[char] return True
6、BFS代码模板
def BFS(graph, start, end): queue = [] queue.append([start]) while queue: node = queue.pop() visited.add(node) process(node) nodes = generate_related_nodes(node) queue.push(nodes)
7、DFS代码模板(递归写法)
visited = set() def dfs(node, visited): if node in visited: return visited.add(node) for next_node in node.children(): if not next_node in visited: dfs(next_node, visited)
8、DFS代码模板(非递归写法)
def DFS(self, tree): if tree.root is None: return [] visited, stack = [], [tree.root] while stack: node = stack.pop() visited.add(node) process(node) nodes = generate_related_nodes(node) stack.push(nodes)