task13,leetcode:160,169,206-python

160.相交链表

此题必须分享的一个双指针图解算法,已经熟悉的也可以去看一下动画哦,超级有爱!!!!双指针法,浪漫相遇

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        node1,node2 = headA,headB
        while node1 != node2:
            node1 = node1.next if node1 else headB
            node2 = node2.next if node2 else headA
        return node1

时间复杂度O(n),空间复杂度O(1)

169.多数元素

详细分析见:leetcode 解法五:Boyer-Moore 投票算法。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        maxc_num = float('inf')            # 用来计算当前的出现次数最多的num
        count = 0
        for num in nums:
            if num == maxc_num:
                count += 1
            else:
                count -= 1
                if count < 0:
                    maxc_num = num
                    count = 1
        return maxc_num

时间复杂度O(n),空间复杂度O(1)

206.反转链表

经典的链表入门题,可以草纸上画一下链表之间的变化情况。

# 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:
        pre, cur = None, head
        while cur:
            # 下面的过程结合草稿纸来画一下就比较容易理解了
            # cur.next在最开始的时候一定要用指针保存一下,
            # 因为cur.next=pre后原来的cur.next就获取不到了
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

时间复杂度O(n),空间复杂度O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值