【汉明距离总和】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)]
相关推荐
陈随易1 小时前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
belldeep2 小时前
python:genesis-world, Genesis-Embodied-AI
人工智能·python·ai·genesis
ss2733 小时前
为什么PostgreSQL适合AI场景?
数据库·人工智能·postgresql
瑞克-桑切斯3 小时前
7、MySQL 慢查询排查与优化实战指南
java·服务器·数据库
Dream-Y.ocean3 小时前
鸿蒙PC平台宅匠 3D 室内设计适配实战:基于 Electron 壳方案的 Three.js 双渲染引擎与参数化户型编辑器开发
javascript·3d·harmonyos
benchmark_cc3 小时前
A 股、港股、美股如何建立统一的标的主数据格式?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
z06.4 小时前
MySQL索引
数据库·mysql
维克兜率天4 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
考虑考虑4 小时前
Posrgresql恢复.backup文件
数据库·后端·postgresql
Csvn4 小时前
性能监控
前端