Leetcode习题只出现一次的数字,环形链表I,II

只出现一次的数字

class Solution:

  def singleNumber(self, nums: List[int]) -> int:

     return reduce(lambda x,y: x^y, nums) #XOR

环形链表

  class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False
            
        slow=head  #慢指针
        fast=head.next #快指针

        while slow!=fast:
            if not fast or not fast.next:
                return False  #如果两个都是快的则循环不会执行

            slow=slow.next
            fast=fast.next.next 

        return True #快慢指针相遇返回TRUE,说明存在闭环

环形链表II

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if not head:
            return None   
   
        fast,slow=head,head #快慢指针同时出发
        while slow.next and fast.next and fast.next.next:  
            slow=slow.next #慢指针每次走一步
            fast=fast.next.next #快指针每次走两步

            if slow==fast: #如果有环继续找入口
                break

        else:
            return None

        slow=head #慢指针从头开始
        while slow!=fast: 
            #相遇的指针慢指针从头开始,快指针从相遇地方开始每次走一步,直到再次相遇
            slow=slow.next
            fast=fast.next
        return slow
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值