【汉明距离总和】python刷题记录

R4-数与位篇

python 复制代码
class Solution:
    def totalHammingDistance(self, nums: List[int]) -> int:
        #创建计数器
        trie=Counter()
        max_bit=len(bin(max(nums)))-2
        ret=0
        for i,num in enumerate(nums):
            for j in range(max_bit):
                #一位位地取出来
                bit=(num>>j)&1
                if bit:
                    ret+=i-trie[j]
                    trie[j]+=1
                else:
                    ret+=trie[j]
        return ret

ps:

counter的用法

python 复制代码
from collections import Counter

# 初始化一个空的 Counter 对象
trie = Counter()

# 添加一些元素
trie.update(['a', 'b', 'a', 'c', 'b', 'a'])

# 查看每个元素的出现次数
print(trie)  # 输出 Counter({'a': 3, 'b': 2, 'c': 1})

# 获取元素 'a' 的计数
print(trie['a'])  # 输出 3

# 如果元素不存在,返回0
print(trie['d'])  # 输出 0

# 添加更多元素
trie['a'] += 1  # 等同于 trie.update(['a'])
print(trie)  # 输出 Counter({'a': 4, 'b': 2, 'c': 1})

# 获取出现次数最多的元素
print(trie.most_common(1))  # 输出 [('a', 4)]
相关推荐
花酒锄作田8 小时前
Pydantic校验配置文件
python
hboot8 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
lichenyang45312 小时前
Docker 学习笔记(一):为什么需要镜像、容器和仓库?
前端
kyriewen12 小时前
别再对着 TypeScript 报错发呆了:我把 10 个最常见的红色波浪线翻译成了人话
前端·javascript·typescript
IT_陈寒12 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
free3513 小时前
从 0 实现一个 Tiny JavaScript VM:项目架构拆解
javascript
GBASE13 小时前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
奇奇怪怪的13 小时前
Embedding 模型 10+ 横向评测
前端
陈广亮13 小时前
Monorepo 从 0 到 1 实操指南 2026 版:pnpm catalogs + Turborepo 2.x + changesets 全链路
前端