Leetcode top 200

1. Two Sum

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

2. Add Two Numbers

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        h1 = ListNode(-1)
        n1, n2, n3 = l1, l2, h1
        remain,curSum = 0,0
        while n1 or n2:
            curSum = 0
            if n1:
                curSum += n1.val
                n1 = n1.next
            if n2:
                curSum += n2.val
                n2 = n2.next
            curSum += remain
            cur = ListNode(curSum%10)
            remain = curSum//10
            n3.next = cur
            n3 = n3.next
        if remain:
            cur = ListNode(remain)
            n3.next = cur
        return h1.next

时间复杂度:O(m+n)

空间复杂度:O(1)

3.Longest Substring Without Repeating Characters

使用字典记录历史位置

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        usedChars = {}
        maxLen,begin = 0,0
        for i,char in enumerate(s):
            if char in usedChars:
                begin =max(usedChars[char]+1,begin)
            usedChars[char] = i
            maxLen = max(maxLen,i-begin+1)
        return maxLen

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>