python3刷Leetcode 1-3

  • 刚切换到python3发现类函数的不同
# python3
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
# python2
class Solution(object):
    def twoSum(self, nums, target):
  • 其中nums后面的“: List[int]”,target后面的“: int” 都是python3新增的类型注解,而->List[int]是返回值注解,作用是标注一下类型,增加程序的可读性。
  • 使用前需要from typing import List。(当然Leetcode已经自动import了)

进入正题

第一题:TwoSum

  1. 暴力解法,直接双重循环,寻找下标不同的两数是否等于target。
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i,n1 in enumerate(nums):
            for j,n2 in enumerate(nums):
                if(i!=j):
                    if(n1+n2==target):
                        return [i,j]
# 这段代码在python3中超时了,而在python2中没有超时。使用Java也不会超时。
  1. 在一次遍历中,使用一个字典模拟哈希表,来存放已经遍历的值。如果(target-当前值)的结果存在于哈希表中,则返回两者索引即可。
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {
    
    }
        for i, n in enumerate(nums):
            # if (map.get(target-n)!=None):
            if (target-n in map):
                return [map.get(target-n),i]
            map[n] = i
  • 用到的一些python技巧:
    • 枚举一个数组中的所有元素的时候,使用enumerate可以同时枚举下标。
    • Python中的哈希表称为字典 {}
    • 判断字典中是否包含某个元素,使用 n in map 判断

第二题:两数相加

# 评论区的简洁写法
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = p = ListNode(None) # dummyhead  
        s = 0  # 进位
        while l1 or l2 or s:  
            s += (l1.val if l1 else 0) + (l2.val if l2 else 0)
            p.next = ListNode(s % 10)
            p = p.next
            s //= 10 
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next

第三题:无重复字符的最长子串

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        dict = {
    
    }
        res = 0
        left = -1 # 注意边界,最开始左边是-1。这样第一个元素索引0,0-(-1) = 1。才正确
        for i, n in enumerate(s):
            if n in dict:
                if dict.get(n) > left:
                    left = dict.get(n)
            res = max(res,i-left)
            dict[n] = i
        return res;

猜你喜欢

转载自blog.csdn.net/o_ogou/article/details/107226831
1-3