【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree
2016-01-13 15:37
731 查看
今天做了三道LeetCode上的简单题目,每道题都是用c++和Python两种语言写的。由于c++版的代码网上比較多。所以就仅仅分享一下Python的代码吧,刚学完Python的基本的语法,做做LeetCode的题目还是不错的,对以后找工作面试也有帮助!
刚開始就从AC率最高的入手吧!
1.Given an array of integers, every element appears twice except
for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
開始纠结于线性时间复杂度和不要额外的存储空间。思路是遍历一遍数组。想象成翻硬币。碰到一次就翻面,再碰到就翻回来了。剩下的那个仍是背面的就是仅仅出现一次的。可是这样的思路就势必要有额外的存储空间。后来看了别人的思路,原来所有异或就能够了。由于A XOR A =0,0 XOR any = any。简单多了。
2.Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
递归寻找左子树和右子树的深度,取二者较大的,再加上根的深度1。即为答案。
刚開始就从AC率最高的入手吧!
1.Given an array of integers, every element appears twice except
for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
開始纠结于线性时间复杂度和不要额外的存储空间。思路是遍历一遍数组。想象成翻硬币。碰到一次就翻面,再碰到就翻回来了。剩下的那个仍是背面的就是仅仅出现一次的。可是这样的思路就势必要有额外的存储空间。后来看了别人的思路,原来所有异或就能够了。由于A XOR A =0,0 XOR any = any。简单多了。
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): result = 0 for i in A: result = result ^ i return result
2.Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
递归寻找左子树和右子树的深度,取二者较大的,再加上根的深度1。即为答案。
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def maxDepth(self, root): if root is None: return 0 else: return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
相关文章推荐
- 关于Numpy,Scipy,Scikit-learn的查询文档
- python二维数组
- selenium-webdriver(python) (十) 如何处理下拉框
- python socket编程详细介绍
- python数据类型转换
- Python编程的例子----股票数据接口
- python 的内嵌time模板翻译及说明[转]
- 笨办法学Python学习笔记 练习21
- Python数据类型学习笔记
- Python 2.5.9 filter
- Python的sys.stdout、sys.stdin重定向
- 如何制作python安装模块(setup.py)
- python getopt使用
- Python 获得命令行参数的方法
- python 字典操作
- 还不错的python学习博客
- python 字符串操作
- Python之路:堡垒机实例以及数据库操作
- python 元组操作
- python 列表操作