2024-12-31 10:49阅读: 11评论: 0推荐: 0

python中的set()

在 Python 中,set() 是用来创建集合的内置函数。集合是一个无序且不重复的元素集合,在 LeetCode 刷题中经常用来处理去重、集合操作(如交集、并集、差集)、快速查找等问题。

基本特性

  1. 无序性:集合中的元素没有顺序。
  2. 不重复性:集合会自动去除重复元素。
  3. 可变性:集合本身可以修改,但其中的元素必须是可哈希的(如字符串、数字、元组等)。

常见用法和语法

1. 创建集合

  • 空集合
    s = set() # 空集合,注意 {} 是空字典
    print(s) # 输出: set()
  • 通过列表或字符串创建
    s = set([1, 2, 2, 3])
    print(s) # 输出: {1, 2, 3}
    s = set("leetcode")
    print(s) # 输出: {'l', 'e', 't', 'c', 'o', 'd'}

2. 集合操作

  • 添加元素
    s = {1, 2, 3}
    s.add(4)
    print(s) # 输出: {1, 2, 3, 4}
  • 删除元素
    s = {1, 2, 3}
    s.remove(2) # 若元素不存在会报错
    s.discard(4) # 若元素不存在不会报错
    print(s) # 输出: {1, 3}
  • 清空集合
    s.clear()
    print(s) # 输出: set()

3. 集合判断操作

  • 检查元素是否存在
    s = {1, 2, 3}
    print(1 in s) # 输出: True
    print(4 in s) # 输出: False
  • 检查子集或超集
    a = {1, 2}
    b = {1, 2, 3}
    print(a.issubset(b)) # 输出: True
    print(b.issuperset(a)) # 输出: True

4. 集合间运算

  • 交集
    a = {1, 2, 3}
    b = {2, 3, 4}
    print(a & b) # 输出: {2, 3}
    print(a.intersection(b)) # 输出: {2, 3}
  • 并集
    print(a | b) # 输出: {1, 2, 3, 4}
    print(a.union(b)) # 输出: {1, 2, 3, 4}
  • 差集
    print(a - b) # 输出: {1}
    print(a.difference(b)) # 输出: {1}
  • 对称差集(非共有元素)
    print(a ^ b) # 输出: {1, 4}
    print(a.symmetric_difference(b)) # 输出: {1, 4}

5. 集合推导式

类似列表推导式,但用于创建集合。

s = {x**2 for x in range(5)}
print(s) # 输出: {0, 1, 4, 9, 16}

LeetCode 中常用场景

  1. 去重

    nums = [1, 2, 2, 3, 4, 4]
    unique = set(nums)
    print(unique) # 输出: {1, 2, 3, 4}
  2. 查找重复元素

    nums = [1, 2, 3, 4, 3]
    seen = set()
    for num in nums:
    if num in seen:
    print("Found duplicate:", num) # 输出: Found duplicate: 3
    seen.add(num)
  3. 检查两个数组的交集

    nums1 = [1, 2, 2, 3]
    nums2 = [2, 3, 4]
    result = list(set(nums1) & set(nums2))
    print(result) # 输出: [2, 3]
  4. 检查唯一字符

    s = "leetcode"
    print(len(s) == len(set(s))) # 输出: False (有重复字符)
  5. 找到数组中的缺失数字

    nums = [0, 1, 3]
    n = len(nums)
    missing = set(range(n+1)) - set(nums)
    print(missing.pop()) # 输出: 2
  6. 判断单词能否由集合中的字母拼出

    word = "apple"
    letters = {'a', 'p', 'l', 'e'}
    print(set(word).issubset(letters)) # 输出: True

效率优势

  • 集合的查找和添加操作时间复杂度为 ( O(1) ),适合用于快速判断某元素是否存在。
  • 集合操作(交集、并集、差集)在处理大规模数据时效率高。

在 LeetCode 中,使用集合可以显著优化代码性能,特别是在涉及重复检查、集合操作的题目中。

本文作者:清澈的澈

本文链接:https://www.cnblogs.com/lmc7/p/18643493

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   清澈的澈  阅读(11)  评论(0编辑  收藏  举报
评论
收藏
关注
推荐
深色
回顶
收起
点击右上角即可分享
微信分享提示