【汉明距离总和】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)]
相关推荐
ℋᙚᵐⁱᒻᵉ鲸落24 分钟前
移动端滑动手势冲突:overflow: auto导致外层横向滑动失效
前端·javascript·css·vue.js·html
圣保罗的大教堂1 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
oradh1 小时前
Oracle TX 锁 Mode 4(Share)问题排查总结
数据库·oracle·tx 锁 mode 4·oracle tx 锁
yi.Ist2 小时前
数据定义语言-DDL操作
数据库·学习·mysql·oracle·大海豚
默_笙2 小时前
🎃 前端学了 Next.js,后端该学啥?NestJS 就是 Node 版的蜜雪冰城
前端·javascript
傲笑风2 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
维基框架3 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
前端snow3 小时前
ai agent --- 实现 openclaw 定时间效果
前端
码云之上3 小时前
换模型之后,Chatbot 为什么要自己做 compact?
前端·agent·前端工程化
এ慕ོ冬℘゜3 小时前
navigator 导航对象 BOM制作方法
javascript