Algorithms to live by . 算法用在生活中的法则
priority queue 任务密度 = 重要程度
kelly formula 凯利公式 赌博
game theory 博弈论
需要背诵的算法模板:
遍历每一个map:
从start开始,不停的去找儿子
BFS:
从start开始,把相邻的放在node数组里面,然后去遍历相邻的
二分法:
DP的模板:
两步法:
1.状态的定义
2.状态的转移方程
位运算:
x & 1 == 1 x为奇数
x & 1 == 0 x为偶数
x = x&(x-1) 清零最低位的1
x = x & -1 得到最低位的1
python 可以实现同时交换两数:
x,y = y,x
经典题目,反转链表:
基础方法,分开写:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, prev= head, None
temp = cur
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
问题:python同时赋值:
错误代码:
正确代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, prev = head, None
while cur:
cur.next,prev,cur = prev,cur,cur.next
return prev
1721.
思路和心得:
1.快慢指针的经典用法
快慢指针用法挺多
1.n等分
2.检测有无环
3.从后数第几个
用list去记录每一个节点:
暴力破解:非常慢,超出时间限制,完全没有必要
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
list = []
cur = head
while cur:
list.append(cur)
cur = cur.next
if k == 1:
node1 = head
node2 = list[-1]
head = node1
head.next = list[1]
list[-2].next = node1
node1.next = None
else:
node1 = list[k-1]
node2 = list[-k]
list[k-2].next = node2
node2.next = list[k]
list[-k-1].next = node1
node1.next = list[-k+1]
return head
第二种解法:只记录要调换位置的相关节点:
corner case: k=1时
链表题如果遇到交换节点或怎样,可以考虑在head前面再增加一个dummy node从而使循环更加方便
24.两两交换节点:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
cur = ListNode(0)
cur.next = head
if head and head.next:
head = head.next
while cur and cur.next and cur.next.next:
f = cur.next
s = f.next
t = s.next
f.next = t
s.next = f
cur.next = s
cur = cur.next.next
return head