Leetcode Python3刷题笔记

1-5题 

1. 两数之和

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)-1):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]

这种方法运行时间长,因为存在两个循环。优化方式:减少循环个数、

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)-1):
            res=target-nums[i]
            if res in nums[i+1:]:
                return [i, nums[i+1:].index(res)-i+1]

注意,因为返回的index不可以重复,第二个index必须写为nums[i+1:].index(res)-i+1,而不能是nums.index(res)


2. 两数相加

链表

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode],carry=0) -> Optional[ListNode]:
        #递归边界
        if l1 is None and l2 is None:
            return ListNode(carry) if carry else 0
        #确保l1是较大的那个数,因为要返回l1
        if l1 is None:
            l1,l2=l2,l1
        carry+=l1.val+(l2.val if l2 else 0)
        l1.val=carry%10
        addTwoNumbers(l1.next, l2.next if l2 else None, carry//10)
        return l1


3. 无重复字符的最长子串

字符串

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        ans=left=0
        window=set()
        for right,c in enumerate(s):
            while c in window:
                window.remove(s[left])
                left+=1
            window.add(c)
            ans=max(ans,right-left+1)
        return ans

90-96题


92. 反转链表 II

链表

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        dummy=ListNode(next=head)
        p0=dummy
        for _ in range(left-1):
            p0=p0.next
        pre=None
        cur=p0.next
        for _ in range(right-left+1):
            nxt=cur.next
            cur.next=pre
            pre=cur
            cur=nxt
        p0.next.next=cur
        p0.next=pre
        return dummy.next

206-210题

206. 反转链表

链表

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre=None
        cur=head
        while cur!=None:
            nxt=cur.next
            cur.next=pre
            pre=cur
            cur=nxt
        return pre

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值