leetcode 1-225简单题(python)

1 两数之和

利用哈希表减小时间复杂度

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict={}
        for i,num in enumerate(nums):
            t2=target-num
            if t2 in dict:
                return [i,dict[t2]]
            dict[num]=i
        return []

9 回文数

这里主要是计算倒序数判断是否相等。

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
            return False
        cur=0
        num=x
        while num !=0:
            cur=cur*10+num%10
            num//=10
        return cur==x

13 罗马数字转整数

这里是判断如果后面的比前面的大,那么前面的数字就应该减去,加上了的话就减2倍。

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dict={'I': 1,'V': 5,'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000}
        sum=dict[s[0]]
        for char in range(1,len(s)):
            if dict[s[char]]>dict[s[char-1]]:
                sum=sum-2*dict[s[char-1]]
            sum+=dict[s[char]]
        return sum

14 最长公共前缀

注意判断strs里的长度如果最大的就是当前的遍历值的情况。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return []
        length=len(strs[0])
        count=len(strs)
        for char in range(length):
            c=strs[0][char]
            if any(char==len(strs[j]) or c!= strs[j][char] for j in range(1,count)):
                return strs[0][:char]
        return strs[0]

20 有效的括号

主要使用栈(先进后出)的方法实现,注意pop不能是空栈。

class Solution(object):
    def isValid(self, s):
        dict={'{':'}','[':']','(':')','?':'?'}
        stack=['?']
        for i in s:
            if i in dict:
                stack.append(i)
            elif dict[stack.pop()] != i:return False
        return len(stack)== 1

21 合并两个有序链表 

1、递归法 

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        if not list1:return list2
        if not list2:return list1
        if list1.val<=list2.val:
            list1.next=self.mergeTwoLists(list1.next,list2)
            return list1
        else: 
            list2.next=self.mergeTwoLists(list2.next,list1)
            return list2

2、迭代法

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        prehead=ListNode(-1)
        pre=prehead
        while list1 and list2:
            if list1.val<list2.val:
                pre.next=list1
                list1=list1.next
            else:
                pre.next=list2
                list2=list2.next
            pre=pre.next
        pre.next=list1 if not list2 else list2
        return prehead.next

26 删除有序数组中的重复项

添加复制的小判断,大于等于1才进行复制。 

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return []
        left=0
        needle=1
        while needle<len(nums):
            if nums[left]!=nums[needle]:
                if needle-left>1:
                    nums[left+1]=nums[needle]
                left=left+1
            needle+=1
        return left+1

27 移除元素

class Solution(object):
    def removeElement(self, nums, val):
        q=0
        count=len(nums)
        for p in range(count):
            if nums[p] != val:
                nums[q]=nums[p]
                q+=1
        return q

 28 字符串中第一个匹配的下标

class Solution(object):
    def strStr(self, haystack, needle):
        result=haystack.find(needle)
        return result

35 搜索插入位置

本题用二分法实现。

class Solution(object):
    def searchInsert(self, nums, target):
        length=len(nums)
        if target>nums[length-1]:
            return length
        left=0
        right=length-1
        while left<right:
            mid=(left+right)//2
            if nums[mid]<target:
                left=mid+1
            else:
                right=mid
        return left

58 最后一个单词的长度

class Solution(object):
    def lengthOfLastWord(self, s):
        char=s.split()
        result=len(char[-1])
        return result

不用split:(速度好像快一点)

class Solution(object):
    def lengthOfLastWord(self, s):
        count=0
        for char in s[::-1]:
            if char ==' ':
                if count==0:
                    continue
                else: break
            count+=1
        return count

66 加一

class Solution(object):
    def plusOne(self, digits):
        n=len(digits)
        carry=1
        for i in range(n-1,-1,-1):
            digits[i]+=carry
            carry=digits[i]//10
            digits[i] %= 10
        if carry:
            digits.insert(0,1)
        return digits

67 二进制求和

class Solution(object):
    def addBinary(self, a, b):
       i=len(a)-1
       j=len(b)-1
       result=''
       carry=0
       while i>=0 or j>=0 or carry:
           sum=0
           if i>=0:
               sum+=int(a[i])
           if j>=0:
               sum+=int(b[j])
           sum+=carry
           carry=sum//2
           char=str(sum%2)
           result=char+result
           i-=1
           j-=1
       return result

68 x的平方根 

class Solution:
     def mySqrt(self,x):
        if x<2:
            return x
        left=1
        right=x//2
        while left<=right:
            mid=(left+right)//2
            sqrt=mid*mid
            if sqrt<x:
                ans=mid
                left=mid+1
            elif sqrt>x:
                right=mid-1
            else: return mid
        return ans

70 爬楼梯

class Solution(object):
    def climbStairs(self, n):
        if n==1:
            return 1
        pre1=1
        pre2=1
        for i in range(1,n):
            r=pre1+pre2
            pre1=pre2
            pre2=r
        return r

83 删除链表中的重复元素

class Solution(object):
    def deleteDuplicates(self, head):
        if not head:
            return head
        cur=head
        while head.next:
            if head.val==head.next.val:
                head.next=head.next.next
            else:
                head=head.next
        return cur

 88 合并两个有序数组

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        nums1[m:]=nums2
        nums1.sort()
        return nums1

94 二叉树的中序遍历

class Solution(object):
	def inorderTraversal(self, root):
		"""
		:type root: TreeNode
		:rtype: List[int]
		"""
		# res = []
		# def dfs(root):
		# 	if not root:
		# 		return
		# 	# 按照 左-打印-右的方式遍历	
		# 	dfs(root.left)
		# 	res.append(root.val)
		# 	dfs(root.right)
		# dfs(root)
		# return res
        # 上面是递归
		res = []
		stack = []
		while stack or root:
			# 不断往左子树方向走,每走一次就将当前节点保存到栈中
			# 这是模拟递归的调用
			if root:
				stack.append(root)
				root = root.left
			# 当前节点为空,说明左边走到头了,从栈中弹出节点并保存
			# 然后转向右边节点,继续上面整个过程
			else:
				tmp = stack.pop()
				res.append(tmp.val)
				root = tmp.right
		return res

100 相同的树

class Solution:
    def isSameTree(self, p, q):
        if not p and not q:
            return True
        elif not p or not q:
            return False
        elif p.val != q.val:
            return False
        else:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

101 对称二叉树

class Solution(object):
	def isSymmetric(self, root):
		"""
		:type root: TreeNode
		:rtype: bool
		"""
		if not root or not (root.left or root.right):
			return True
		# 用队列保存节点	
		queue = [root.left,root.right]
		while queue:
			# 从队列中取出两个节点,再比较这两个节点
			left = queue.pop(0)
			right = queue.pop(0)
			# 如果两个节点都为空就继续循环,两者有一个为空就返回false
			if not (left or right):
				continue
			if not (left and right):
				return False
			if left.val!=right.val:
				return False
			# 将左节点的左孩子, 右节点的右孩子放入队列
			queue.append(left.left)
			queue.append(right.right)
			# 将左节点的右孩子,右节点的左孩子放入队列
			queue.append(left.right)
			queue.append(right.left)
		return True
        # if not root:
        #     return True
        # def dfs(left,right):
        #     if not left and not right:
        #         return True
        #     elif not left or not right:
        #         return False
        #     elif left.val != right.val:
        #         return False
        #     return dfs(left.left,right.right) and dfs(left.right,right.left)
        # return dfs(root.left,root.right)
        # 以上是递归法

104 二叉树的最大深度

class Solution(object):
    def maxDepth(self, root):
        if not root:
            return 0
        else:
            left_h=self.maxDepth(root.left)
            right_h=self.maxDepth(root.right)
            return max(left_h,right_h)+1

108 将有序数组转化为搜索二叉树

class Solution(object):
    def sortedArrayToBST(self, nums):
        def helper(left,right):
            if left>right:
                return None
            mid=(left+right)//2
            root=TreeNode(nums[mid])
            root.left=helper(left,mid-1)
            root.right=helper(mid+1,right)
            return root

        return helper(0,len(nums)-1)

110 平衡二叉树

class Solution:
    def isBalanced(self, root) :
        def recur(root):
            if not root: return 0
            left = recur(root.left)
            if left == -1: return -1
            right = recur(root.right)
            if right == -1: return -1
            return max(left, right) + 1 if abs(left - right) <= 1 else -1

        return recur(root) != -1

111 二叉树的最小深度

class Solution(object):
    def minDepth(self, root):
        if not root:
            return 0
        lh=self.minDepth(root.left)
        rh=self.minDepth(root.right)
        if not (root.left and root.right):
            return lh+rh+1
        else:
            return min(lh,rh)+1

112 路径总和

class Solution(object):
    def hasPathSum(self, root, targetSum):
        if not root:
            return False
        if not root.left and not root.right:
            return root.val==targetSum
        return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val) 

118 杨辉三角

class Solution(object):
    def generate(self, numRows):
        if numRows==0:
            return []
        res=[[1]]
        while len(res)<numRows:
            new=[a+b for a,b in zip(res[-1]+[0],[0]+res[-1])]
            res.append(new)
        return res

 借位相加。

119 杨辉三角二

class Solution(object):
    def getRow(self, rowIndex):
        row=[1]
        for i in range(1,rowIndex+1):
            new=row[-1]*(rowIndex-i+1)/i
            row.append(new)
        return row

 

121 买卖股票的最佳时机

class Solution(object):
    def maxProfit(self, prices):
        minprice=int(1e9)
        money=0
        for i in prices:
            money=max(i-minprice,money)
            minprice=min(minprice,i)
        return mone

 125 验证回文串

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        # if not s:
        #     return True
        # sgood=''.join(ch.lower() for ch in s if ch.isalnum())
        # return sgood==sgood[::-1]
        # 在当前字符串上实现
        if not s:
            return True
        right=len(s)-1
        left=0
        while left<right:
            while left<right and not s[left].isalnum():
                left+=1
            while left<right and not s[right].isalnum():
                right-=1
            if left<right:
                if s[left].lower() != s[right].lower():
                    return False
                left,right=left+1,right-1
        return True

136 只出现一次的数字

return reduce(lambda x,y:y^x, nums)
  1. reduce()函数是Python内置的函数,它接受一个函数和一个可迭代对象作为参数,然后将该函数累积地应用到可迭代对象的元素上,从左到右。在这个代码中,reduce()函数接受了一个lambda函数和一个名为nums的可迭代对象作为参数。

  2. lambda x, y: y ^ x:这是一个匿名函数,其中xy是函数的两个参数。函数体是y ^ x,表示对yx进行异或操作。

  3. nums:这是一个可迭代对象,可能是一个列表、元组或其他可迭代对象。

  4. reduce(lambda x, y: y ^ x, nums):这行代码的作用是将可迭代对象nums中的所有元素依次进行异或操作,并返回最终结果。

异或操作(^)是一种位运算,对于每一对比特位,当相同则结果为0,不同则结果为1。在这种情况下,连续异或操作可以将一系列数字彼此之间进行异或,最终得到一个结果。

141 环形链表

class Solution:
    def hasCycle(self, head) :
        if not head or not head.next:
            return False
        slow = fast = head  # 乌龟和兔子同时从起点出发
        while fast and fast.next:
            slow = slow.next  # 乌龟走一步
            fast = fast.next.next  # 兔子走两步
            if fast == slow:  # 兔子追上乌龟(套圈),说明有环
                return True
        return False  # 访问到了链表末尾,无环

 144 二叉树的前序遍历

这里的递归的方法,还可以用迭代法写

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        def preorder(root: TreeNode):
            if not root:
                return
            res.append(root.val)
            preorder(root.left)
            preorder(root.right)
        
        res = list()
        preorder(root)
        return res

145 二叉树的后续遍历

首先是递归,然后是迭代。 

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        def dfs(root):
            if not root:
                return
            dfs(root.left)
            dfs(root.right)
            res.append(root.val)
        res=[]
        dfs(root)
        return res
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return list()
        
        res = list()
        stack = list()
        prev = None

        while root or stack:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if not root.right or root.right == prev:
                res.append(root.val)
                prev = root
                root = None
            else:
                stack.append(root)
                root = root.right
        
        return res

 160 相交链表

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return null
        p1=headA
        p2=headB
        while p1 != p2:
            p1=p1.next if p1 else headB
            p2=p2.next if p2 else headA
        return p1

168 Excel列表名称

这里要注意的是26进制是0-25表示,题目是1-26对应字母。

class Solution(object):
    def convertToTitle(self, columnNumber):
        """
        :type columnNumber: int
        :rtype: str
        """
        char=''
        while columnNumber>0:
            columnNumber-=1
            num=columnNumber%26
            char=chr(num+ord('A'))+char
            columnNumber=columnNumber//26
        return char

169 多数元素

1、哈希表:

collections.Counter 是 Python 标准库中 collections 模块提供的一个类,用于对可迭代对象中的元素进行计数。它返回一个字典,其中键是可迭代对象中的元素,值是该元素在可迭代对象中出现的次数。

import collections

counter = collections.Counter(iterable)

iterable是一个可迭代的对象,collections.Counter() 返回的对象是一个 Counter 类的实例

nums = [1, 2, 3, 1, 1, 2, 3, 1, 2, 2]
import collections

counter = collections.Counter(nums)
print(counter)
>>>
Counter({1: 4, 2: 3, 3: 2})

max() 函数是 Python 内置函数之一,用于返回可迭代对象中的最大值。它的语法如下:

max(iterable, *[, key, default])

'''
iterable 是一个可迭代对象,如列表、元组、集合等。
key 是一个函数,用于指定一个可调用对象,用于从每个元素中提取用于比较的键。默认为 None,表示直接比较元素本身的大小。
default 是一个可选参数,用于指定当可迭代对象为空时返回的默认值。如果不提供 default 参数并且可迭代对象为空,那么会引发 ValueError 异常。
'''
# 示例 1:找出列表中的最大值
numbers = [1, 5, 3, 9, 7]
max_number = max(numbers)
print(max_number)  # 输出:9

# 示例 2:找出字符串中 ASCII 值最大的字符
text = "Hello"
max_char = max(text)
print(max_char)  # 输出:o

# 示例 3:使用 key 函数自定义比较规则
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 70},
    {"name": "Charlie", "score": 95}
]
top_student = max(students, key=lambda x: x["score"])
print(top_student)  # 输出:{'name': 'Charlie', 'score': 95}

 解题: 

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get)
'''
key=counts.get 和 key=lambda x: counts.get(x) 都会产生相同的结果,
都会将每个元素作为参数传递给 counts.get() 函数.
'''

时间复杂度:O(n);空间复杂度:O(n)

2、排序法

最中间的元素一定是众数。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums) // 2]
'''
时间复杂度:O(nlog⁡n)。
空间复杂度:O(log⁡n)。
'''

 3、摩尔投票法

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = 0
        candidate = None

        for num in nums:
            if count == 0:
                candidate = num
            count += (1 if num == candidate else -1)

        return candidate

171 Excel表列序号

是168思想反着来的。

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        number, multiple = 0, 1
        for i in range(len(columnTitle) - 1, -1, -1):
            k = ord(columnTitle[i]) - ord("A") + 1
            number += k * multiple
            multiple *= 26
        return number

191 位1的个数

1、循环

'''生成器表达式的基本语法是 (expression for item in iterable if condition)'''
# 将列表中的每个元素加倍
doubled = (x * 2 for x in [1, 2, 3, 4, 5])
print(list(doubled))  # 输出: [2, 4, 6, 8, 10]
# 仅保留偶数
even_numbers = (x for x in range(10) if x % 2 == 0)
print(list(even_numbers))  # 输出: [0, 2, 4, 6, 8]
在Python中,<< 是位运算符,表示左移操作符。它用于将一个数的二进制表示向左移动指定的位数。
例如,对于 x = 5(二进制表示为 101),执行 x << 2 将得到 10100,即十进制的 20。
这是因为 101 左移两位后变成了 10100,低位补0。

1<<i 是一个位运算操作,它将十进制数 1 左移 i 位。这意味着我们生成了一个只有第 i 位是 1,其余位都是 0 的二进制数。例如,当 i 为 0 时,结果是 1;当 i 为 1 时,结果是 2;当 i 为 2 时,结果是 4,依此类推。

解题:

class Solution:
    def hammingWeight(self, n: int) -> int:
        ret = sum(1 for i in range(32) if n & (1 << i)) 
        return ret
'''
时间复杂度:O(k),其中 k 是 int 型的二进制位数,k=32。
我们需要检查 n 的二进制位的每一位,一共需要检查 32 位。
空间复杂度:O(1),我们只需要常数的空间保存若干变量。
'''

2、python内置函数

bin(n).count('1')
# bin() 函数用于将整数转换为二进制字符串表示形式
s = "hello world"
count_e = s.count('e')
print(count_e)  # 输出: 1

3、位运算优化

class Solution:
    def hammingWeight(self, n: int) -> int:
        ret = 0
        while n:
            n &= n - 1
            ret += 1
        return ret
'''
时间复杂度:O(log⁡n)。循环次数等于 n 的二进制位中 1 的个数,最坏情况下 n 的二进制位全部为 1。我们需要循环 log⁡n 次。
空间复杂度:O(1),我们只需要常数的空间保存若干变量。
'''

202 快乐数

快慢指针的思想,尤其注意while循环条件

def isHappy(self, n: int) -> bool:  
    def get_next(number):
        total_sum = 0
        while number > 0:
            number, digit = divmod(number, 10)
            total_sum += digit ** 2
        return total_sum

    slow_runner = n
    fast_runner = get_next(n)
    while fast_runner != 1 and slow_runner != fast_runner:
        slow_runner = get_next(slow_runner)
        fast_runner = get_next(get_next(fast_runner))
    return fast_runner == 1

时间复杂度:O(log⁡n)
空间复杂度:O(1)

203 消除链表元素

1、递归法

理解:head.next指向的应该是head.next后移除了val的链表(递归操作)。递归的终止条件head是否为空,如果为空,就返回head([ ])。return的是链表的第一个元素,也就是如果=val就返回head.next。

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return head
        head.next=self.removeElements(head.next,val)
        return head.next if head.val==val else head
时间复杂度:O(n),其中 n 是链表的长度。递归过程中需要遍历链表一次。
空间复杂度:O(n),其中 n 是链表的长度。空间复杂度主要取决于递归调用栈,最多不会超过 n 层。

 2、迭代法

需要初始化一个dummyhead dummyhead.next=head。

注意while循环的条件和return的值。

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return head
        dummy_head = ListNode(0)  # 创建一个值为0的dummy节点
        dummy_head.next = head
        temp=dummy_head
        while temp.next:
            if temp.next.val==val:
                temp.next=temp.next.next
            else:temp=temp.next
        return dummy_head.next

205 同构字符串

有个题解:index()会返回该元素在str内首次出现的index,将"egg"通过该方式转换为[0,1,1],同理如果其他str也是ABB格式,那么转完也应该是[0,1,1]

return True if [s.index(i) for i in s] == [t.index(j) for j in t] else False

哈希表:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        if len(s) != len(t):  # 如果两个字符串长度不同,则它们一定不是同构的
            return False
        
        char_map_s = {}  # 用于存储 s 中字符到 t 中字符的映射关系
        char_map_t = {}  # 用于存储 t 中字符到 s 中字符的映射关系
        
        for char_s, char_t in zip(s, t):  # 遍历 s 和 t 中的字符
            if char_s in char_map_s:  # 如果当前字符已经在 s 中存在映射
                if char_map_s[char_s] != char_t:  # 检查映射关系是否一致
                    return False
            else:
                char_map_s[char_s] = char_t  # 建立 s 到 t 的映射关系
            
            if char_t in char_map_t:  # 如果当前字符已经在 t 中存在映射
                if char_map_t[char_t] != char_s:  # 检查映射关系是否一致
                    return False
            else:
                char_map_t[char_t] = char_s  # 建立 t 到 s 的映射关系
        
        return True  # 遍历完成后没有发现不一致的映射关系,说明两个字符串是同构的

206 反转链表

1、迭代法

我前面是谁,我是谁,我后面是谁。

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        pre=None
        cur=head
        while cur:
            next=cur.next
            cur.next=pre
            pre=cur
            cur=next
        return pre

时间复杂度:O(n);空间复杂度:O(1)

2、递归法

head.next.next=head

需要注意的是 head的下一个节点必须指向 ∅。如果忽略了这一点,链表中可能会产生环。

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        newhead=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return newhead

以1234为例:

1、newhead=re(2);2、调用re(2)  newhead=re(3);3、调用re(3)  newhead=re(4);4、调用re(4)这时head.next=None,返回4;4、跟步骤3对应,newhead=4,继续执行,3.next.next=3,得到4-3;5、跟步骤2 对应 执行re(3)后面部分 得到4-3-2--------省略。

217 存在重复元素

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        list=[]
        for num in nums:
            if num not in list:
                list.append(num)
            else:
                return True
        return False
》》》
超时了!!!!

1、set

用set()集合没有显示超时: set 是一种无序、不重复的数据集合。它类似于数学中的集合,可以存储各种类型的元素,并且确保其中的每个元素都是唯一的。

无序性;唯一性,可变性。

my_set = {1, 2, 3, 4, 5} #{}
my_set = set([1, 2, 3, 4, 5]) #set()

 检查列表中是否包含某个元素的操作的时间复杂度是 O(n),而且还需要进行插入操作,其时间复杂度也是 O(n)。集合使用哈希表实现,所以检查元素是否存在的操作的时间复杂度是 O(1),这使得集合非常适合于查找、删除重复元素等操作。

(列表添加元素没有add,使用的是append和insert)

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        seen = set()  # 使用集合存储已经遍历过的数字
        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False

2、字典

在 Python 中,可以使用字典来实现类似的功能。字典的键就相当于集合中的元素,而字典的值可以是任意类型,但在这里我们可以将值设置为True\None 等占位符。

class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        hash_table = {}
        for x in nums:
            if x in hash_table:
                return True
            hash_table[x] = True
        return False

219 存在重复元素2.0

1、哈希表:字典

在 Python 中, enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环中。

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dict={}
        for i,num in enumerate(nums):
            if num in dict and i-dict[num]<=k:
                return True
            dict[num]=i
        return False

2、集合加滑动窗口

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        jihe=set()
        for i,num in enumerate(nums):
            if i>k:
                jihe.remove(nums[i-k-1])
            if num in jihe:
                return True
            else:
                jihe.add(num)
        return False

222 完全二叉树的节点个数

很容易的递归但是没有利用完全二叉树的特点:

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return self.countNodes(root.left)+self.countNodes(root.right)+1

完全二叉树的定义:它是一棵空树或者它的叶子节点只出在最后两层,若最后一层不满则叶子节点只在最左侧。

class Solution(object):
    def countNodes(self, root):
        #二叉树的层数
        def countlevel(root):
            if not root:
                return 0
            return max(countlevel(root.left),countlevel(root.right))+1
        if not root:
            return 0
        left=countlevel(root.left)
        right=countlevel(root.right)
        if left==right:
            return (1<<left)+self.countNodes(root.right)
        else:
            return (1<<right)+self.countNodes(root.left)

1<<left 是在计算pow(2,left) <<按位左移

225 用队列实现栈

双端队列(deque,全称为 double-ended queue)。

import collections

# 创建一个空的双端队列
my_deque = collections.deque()

my_deque.append(x)
# append(x):在双端队列的右侧添加元素 x。
my_deque.appendleft(x)
# appendleft(x):在双端队列的左侧添加元素 x。
x = my_deque.pop()
# pop():移除并返回双端队列右侧的元素。
x = my_deque.popleft()
# popleft():移除并返回双端队列左侧的元素。
my_deque.extend(iterable)
# extend(iterable):在双端队列右侧扩展,追加一个可迭代对象中的所有元素。
my_deque.extendleft(iterable)
# extendleft(iterable):在双端队列左侧扩展,追加一个可迭代对象中的所有元素。
my_deque.clear()
# clear():清空双端队列中的所有元素。
class MyStack(object):

    def __init__(self):
        self.queue=collections.deque()


    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.queue.append(x)


    def pop(self):
        """
        :rtype: int
        """
        return self.queue.pop()


    def top(self):
        """
        :rtype: int
        """
        return self.queue[-1]


    def empty(self):
        """
        :rtype: bool
        """
        return not self.queue

  • 13
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: LeetCode是一个优秀的在线编程平台,提供了丰富的算法和数据结构目供程序员练习。其中的简单大多可以用Python语言编写,下面为您提供几个常见目的Python版本答案。 1. 两数之和(Two Sum) 目描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 Python版本答案: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if target - x in d: return [d[target - x], i] d[x] = i 2. 反转字符串(Reverse String) 目描述:编写一个函数,其作用是将输入的字符串反转过来。 Python版本答案: class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 3. 回文数字(Palindrome Number) 目描述:判断一个整数是否是回文数,例如:121是回文数,-121不是回文数。 Python版本答案: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False if x == 0: return True str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True 以上只是这几个简单目的Python版本答案,实际上LeetCode上还有很多其他编程语言编写的优秀答案,需要程序员们自己去探索和实践。 ### 回答2: Leetcode是一个流行的在线编程库,提供了许多关于算法和数据结构的目,难度从简单到困难不等。Python是一种易学易用的编程语言,备受程序员欢迎。因此,许多程序员使用Python来解决Leetcode的编程问。下面我将提供一些Python版本的Leetcode简单的答案。 1. 两数之和 目描述:给定一个整数数组和一个目标值,在数组中找到两个数之和等于目标值。 解思路:使用哈希表来存储数组中每个元素的值和索引,然后遍历每个元素时,查找目标值减去当前元素的值是否在哈希表中,如果存在,返回两个值的索引。 Python代码: def twoSum(nums, target): hash_table = {} for i, num in enumerate(nums): complement = target - num if complement in hash_table: return hash_table[complement], i hash_table[num] = i nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target)) # Output: (0, 1) 2. 路径总和 目描述:给定一棵二叉树和一个目标值,判断是否存在从根节点到叶节点的路径,使得路径上所有节点的值相加等于目标值。 解思路:遍历二叉树的所有路径,判断路径上所有节点的值相加是否等于目标值。 Python代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(root, sum): if not root: return False if not root.left and not root.right and root.val == sum: return True return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) sum = 22 print(hasPathSum(root, sum)) # Output: True 3. 最大子序和 目描述:给定一个整数数组,找到一个具有最大和的子数组,返回该子数组的和。 解思路:使用动态规划,定义状态dp[i]表示以第i个数结尾的最大子数组和,则状态转移方程为dp[i] = max(dp[i-1] + nums[i], nums[i])。 Python代码: def maxSubArray(nums): if not nums: return 0 n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp) nums = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(nums)) # Output: 6 总结:以上是三个Python版本的Leetcode简单的答案,它们涉及到哈希表、二叉树、动态规划等算法和数据结构。这些目既考验了程序员的基本功,又是训练算法思维的好工具。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值