只出现一次的数字①
一个整型数组里除了一个数字之外,其他的数字都出现了两次。请写程序找出这个出现一次的数字。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=0
for i in range(len(nums)):
n=nums[i]^n
return n
只出现一次的数字②
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
x=0
y=0
a=0
for i in array:
a^=i
a&=~a+1
for i in array:
if i&a:
x^=i
else:
y^=i
return [x,y]
平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。即左右子树是否高度差<=1
# 暴力方法 对每个结点计算左右高度,进而判断
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if not pRoot:
return True
return abs(self.Depth(pRoot.left)-self.Depth(pRoot.right))<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def Depth(self,root):
if not root:
return 0
return max(self.Depth(root.left),self.Depth(root.right))+1
# 一次历遍法
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if not pRoot:
return True
return self.Depth(pRoot)!=-1
def Depth(self,root):
if not root:
return 0
left=self.Depth(root.left)
# 若有左子树或右子树返回-1,则存在非平衡树
if left == -1:
return -1
right=self.Depth(root.right)
if right == -1:
return -1
if abs(left-right)>1:
return -1
return max(left,right)+1
和为S的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
- 前后两个指针 向中靠近
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
start=0
end=len(array)-1
if not array:
return []
while array[end] > tsum:
end-=1
while end > start:
Sum=array[end]+array[start]
if Sum > tsum:
end-=1
elif Sum==tsum:
return [array[start],array[end]]
else:
start+=1
return []
和为S的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
- 两个指针进行历遍
class Solution:
def FindContinuousSequence(self, tsum):
# write code here
start=1
end=2
res=[]
while end < tsum and end > start:
Sum=((end-start+1)/2.)*(start+end)
if Sum < tsum:
end+=1
elif int(Sum) == tsum:
res.append([i for i in range(start,end+1)])
#res.append(Sum)
end+=1
else:
start+=1
return res