【Leetcode】【python】Hamming Distance, Merge Two Binary Trees
来源:互联网 发布:mysql建立索引 编辑:程序博客网 时间:2024/06/08 03:53
Hamming Distance
题目大意
两个整数的汉明距离是指其二进制不相等的位的个数。
给定两个整数x和y,计算汉明距离。
注意:
0 ≤ x, y < 2^31.
解题思路
异或运算
代码
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x ^ y).count('1')
我提交的
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x_bin = list(bin(x)) y_bin = list(bin(y)) x_bin.reverse() y_bin.reverse() x_judge = [] y_judge = [] for x in x_bin: if x == 'b': break x_judge.append(x) for y in y_bin: if y == 'b': break y_judge.append(y) list_distance = abs(len(x_judge) - len(y_judge)) if len(x_judge) < len(y_judge): for i in range(list_distance): x_judge.append('0') else: for i in range(list_distance): y_judge.append('0') distance = 0 for i in range(len(x_judge)): if x_judge[i] != y_judge[i]: distance += 1 return distance
总结
以后谁和我说二进制异或运算我和谁急
Merge Two Binary Trees
题目大意
给两个二叉树想要合并,有一些结点会重叠而有一些不会,现在想把重叠的结点值变为两者值相加,不重叠的直接用,构建出新的树
解题思路
考察的就是二叉树的遍历,遍历每个结点然后如果重叠(两个二叉树结点都不为空)新结点值便为两者和,不重叠(只有一个结点为空)新结点值为不为空的值,全为空到达底部返跳出。按照这个逻辑进行迭代
联想:二叉树遍历方式有深度优先和广度优先,深度(纵向)优先在Python中一般使用列表,广度优先(横向)一般使用迭代
代码
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 is None and t2 is None: return if t1 is None: return t2 if t2 is None: return t1 t1.val += t2.val t1.right = self.mergeTrees(t1.right, t2.right) t1.left = self.mergeTrees(t1.left, t2.left) return t1
总结
此题做时没有理解这个TreeNode类是怎么用的,看了答案才明白。
后来尝试了:
t1.right.val>> 2t1.left.left.val>> 5
该答案应该是广度优先的迭代方法。
阅读全文
0 0
- 【Leetcode】【python】Hamming Distance, Merge Two Binary Trees
- 【leetcode】 Merge Two Binary Trees
- leetcode[Merge Two Binary Trees]
- Merge Two Binary Trees(leetcode)
- [leetcode]617. Merge Two Binary Trees
- leetcode.617.Merge Two Binary Trees
- [leetcode]: 617. Merge Two Binary Trees
- [Leetcode]617. Merge Two Binary Trees
- LeetCode 617. Merge Two Binary Trees (C++)
- LeetCode 617. Merge Two Binary Trees
- [LeetCode] 617. Merge Two Binary Trees
- LeetCode 617. Merge Two Binary Trees
- 【Leetcode】617. Merge Two Binary Trees
- leetcode 617 merge two binary trees
- [LeetCode]617.Merge Two Binary Trees
- 【LeetCode】617 Merge Two Binary Trees
- LeetCode: 617. Merge Two Binary Trees
- leetcode 617:Merge Two Binary Trees
- 第9章Spark 2.1.0新一代Tungsten优化引擎彻底解析
- OC基础-内存对象管理20
- HDU2521 反素数【因子数量+打表】
- 帧中继(Frame Relay)
- C# Socket的TCP通讯
- 【Leetcode】【python】Hamming Distance, Merge Two Binary Trees
- ssm整合一个user表(配合上一篇的配置文件使用)
- usb中的endpoint(端点)和传输模式
- 51单片机特殊功能寄存器(SFR)介绍
- 中央巡視組進駐北京大學,袁萌為何鳴冤叫屈?
- 基于飞思卡尔微控制器的CAN Bootloader的实现与应用
- DDN(数字数据网)
- 【算法】选择排序(从小到大) 排序范围(0~n-1) n为数组元素个数
- 关于一个程序的“开始——暂停——继续”的一个问题