2021-07-02:学完之后的总结1:背诵的算法模板,不熟悉的链表题,1721,24

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值