LeetCode之LinkList刷题记录博

写在前面:

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

1290. Convert Binary Number in a Linked List to Integer <倒序>

我做链表的第一道题:

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        n = 0
        total = 0
        plist = []
        
        while(head):
            n += 1
            if head.val == 1:
                plist.append(n)
            head = head.next
        
        for x in plist:
            total += pow(2,n-x) 
            print(n,total)
            
        return total

中心思想是要把给的head倒过来计算。有两种比较直接的思路:首先就是一一存出来倒着算,当然还有一种类似的看有人读了一遍长度,再重新读了一遍链表直接算;第二种就是把需要加的index记下来单独拿出来算。我写的是第二种思路。
如果对链表和python的指针不熟,比如像我现在这样,这题的重点就是从非常浅的层次来告诉你head.val == 1head = head.next,以及直接从链表下手能干什么不能干什么。


<Floyd龟兔系列>

876. Middle of the Linked List

明明可以简单做的一道题,翻了很久discussion有绝妙的感悟。还记得大二数据结构课老师讲的检测loop吗!这个快慢指针思想就是可以放进去。放一下快慢指针最经典的用法 :

141. Linked List Cycle

def hasCycle(self, head):
    try:
        slow = head
        fast = head.next
        while slow is not fast:
            slow = slow.next
            fast = fast.next.next
        return True
    except:
        return False

142. Linked List Cycle II

追加一道题,除了判断是否是环以外,还有确定起点的位置。需要用到Floyd算法的思想:

  • 确定有环:slow和fast相遇
  • 确定起点的位置:一个在起点一个在相遇点,一次一步,相遇点即为起点。
    参考代码:
def detectCycle(self, head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            break
    else:
        return None
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dear Slim.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值