2024-12-31 10:54阅读: 28评论: 0推荐: 0

python中的dict()

在 Python 中,dict() 是创建字典的内置函数,字典是一种键值对(key-value pair)的数据结构。由于字典具有高效的键值查找、插入和删除操作,在 LeetCode 刷题中非常常用,尤其是处理映射关系、快速查找、计数、前缀匹配等问题时。


基本特性

  1. 键值对存储:字典中的每个元素是一个键值对,形式为 key: value
  2. 键的唯一性:字典的键必须唯一,重复键会覆盖之前的值。
  3. 可变性:字典支持动态添加、修改和删除键值对。
  4. 键必须可哈希:键可以是字符串、数字或元组等不可变类型,不能是列表或字典。

常见用法和语法

1. 创建字典

  • 空字典
    d = {}
    print(d) # 输出: {}
  • 通过 dict() 创建
    d = dict(a=1, b=2)
    print(d) # 输出: {'a': 1, 'b': 2}
  • 通过键值对创建
    d = {'key1': 'value1', 'key2': 'value2'}
    print(d) # 输出: {'key1': 'value1', 'key2': 'value2'}

2. 访问和修改字典

  • 访问值

    d = {'a': 1, 'b': 2}
    print(d['a']) # 输出: 1

    如果键不存在,直接访问会报错。

  • 使用 get() 方法

    print(d.get('c', 'default')) # 输出: 'default'

    如果键不存在,返回默认值 default

  • 添加或修改键值对

    d['c'] = 3
    print(d) # 输出: {'a': 1, 'b': 2, 'c': 3}

3. 删除元素

  • 使用 del
    del d['a']
    print(d) # 输出: {'b': 2, 'c': 3}
  • 使用 pop()
    value = d.pop('b', 'default')
    print(value) # 输出: 2
    print(d) # 输出: {'c': 3}

4. 遍历字典

  • 遍历键
    for key in d:
    print(key)
  • 遍历值
    for value in d.values():
    print(value)
  • 遍历键值对
    for key, value in d.items():
    print(key, value)

5. 字典推导式

  • 快速创建字典
    squares = {x: x**2 for x in range(5)}
    print(squares) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

LeetCode 中常用场景

1. 统计频率

统计字符或数字的出现次数:

nums = [1, 2, 2, 3, 3, 3]
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
print(count) # 输出: {1: 1, 2: 2, 3: 3}

2. 检查映射关系

判断两个字符串是否存在一一映射:

def isIsomorphic(s, t):
mapping_s_t = {}
mapping_t_s = {}
for c1, c2 in zip(s, t):
if c1 in mapping_s_t and mapping_s_t[c1] != c2:
return False
if c2 in mapping_t_s and mapping_t_s[c2] != c1:
return False
mapping_s_t[c1] = c2
mapping_t_s[c2] = c1
return True

3. 前缀匹配

用于实现 Trie(字典树)相关题目:

class Trie:
def __init__(self):
self.children = {}
self.is_end = False
def insert(self, word):
node = self
for char in word:
if char not in node.children:
node.children[char] = Trie()
node = node.children[char]
node.is_end = True

4. 两数之和

使用字典快速查找补数:

def twoSum(nums, target):
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i

5. 滑动窗口问题

用字典记录窗口内字符频率:

def lengthOfLongestSubstring(s):
char_index = {}
start = max_len = 0
for i, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = i
max_len = max(max_len, i - start + 1)
return max_len

效率优势

  1. 查找:字典的查找操作时间复杂度为 ( O(1) )。
  2. 插入和删除:字典的插入和删除操作也为 ( O(1) ),适合大规模数据的快速操作。
  3. 遍历:遍历时间复杂度为 ( O(n) ),取决于字典中元素的数量。

在 LeetCode 中,利用字典可以显著优化性能,尤其在需要频繁查找、统计或建立映射关系的题目中。

本文作者:清澈的澈

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

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

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