注意,答案只是代表是他人写的代码,正确,但不一定能通过测试(比如超时),列举出来只是它们拥有着独到之处,虽然大部分确实比我的好
100. Same Tree
题目
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路与解答
感觉上应该蛮好做的
只要dfs判断一下就好了吧
def dfs(r1,r2):
if r1 == r2 :return 0
if not (r1 != None and r2 != None):return 1
if r1.val == r2.val:
return dfs(r1.left,r2.left)+dfs(r1.right,r2.right)
else:
return 1
return not dfs(p,q)
感觉第二个判断那里有些怪异。。。双重否定句。。。
修改
def dfs(r1,r2):
if r1 == r2 :return 0
if r1 == None or r2 == None:return 1
if r1.val == r2.val:
return dfs(r1.left,r2.left)+dfs(r1.right,r2.right)
else:
return 1
return not dfs(p,q)
答案
巧妙的递归。。。
def isSameTree(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
树[1,2,3,4,5,6]
会生成这么一个元组
(1, (2, (4, None, None), (5, None, None)), (3, (6, None, None), None))
然后进行比较
def isSameTree(self, p, q):
def t(n):
return n and (n.val, t(n.left), t(n.right))
return t(p) == t(q)
一行
return p and q and p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) or p is q
dfs及bfs的做法蛮有意思的
def isSameTree1(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
else:
return p == q
# DFS with stack
def isSameTree2(self, p, q):
stack = [(p, q)]
while stack:
node1, node2 = stack.pop()
if not node1 and not node2:
continue
elif None in [node1, node2]:
return False
else:
if node1.val != node2.val:
return False
stack.append((node1.right, node2.right))
stack.append((node1.left, node2.left))
return True
# BFS with queue
def isSameTree3(self, p, q):
queue = [(p, q)]
while queue:
node1, node2 = queue.pop(0)
if not node1 and not node2:
continue
elif None in [node1, node2]:
return False
else:
if node1.val != node2.val:
return False
queue.append((node1.left, node2.left))
queue.append((node1.right, node2.right))
return True
35. Search Insert Position
题目
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
思路与解答
感觉上确实很简单
for i,j in enumerate(nums):
if target <= j:
return i
return len(nums)
怎么缩短呢
答案
一行,有想法
return len([x for x in nums if x<target])
理论上这种方法会比较快吧
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] >= target:
right = mid - 1
else:
left = mid + 1
return left
671. Second Minimum Node In a Binary Tree
题目
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn’t any second smallest value.
思路与解答
题目意思是返回一个树里倒数第二小的数?
怎么判断第二大存在真是伤
又要用到无限大了float(‘inf’)
self.amin = root.val
self.bmin = float('inf')
def dfs(r):
if r:
if self.amin < r.val < self.bmin:
self.bmin = r.val
elif r.val == self.amin:
dfs(r.left)
dfs(r.right)
dfs(root)
return self.bmin if self.bmin != float('inf') else -1
答案
大家的想法都很一致嘛,不过他的列表为什么就能传进去,我的amin,bmin就不行
res = [float('inf')]
def traverse(node):
if not node:
return
if root.val < node.val < res[0]:
res[0] = node.val
traverse(node.left)
traverse(node.right)
traverse(root)
return -1 if res[0] == float('inf') else res[0]
很有趣的
result = set()
stack = [root]
while stack:
node = stack.pop()
result.add(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
result = sorted(list(result))
return result[1] if len(result) > 1 else -1
69. Sqrt(x)
题目
Implement int sqrt(int x).
Compute and return the square root of x.
思路与解答
所以怎么算平方根。。。
手动开方方法-百度百科
第一步分成两个一组一段一段的
第二步求平方根,一点一点试
。。。。。。我写一会发现,既然是一点一点试,那我为什么不开始就直接试呢,何必要分段
关键是初值定多少
看起来要超时了
另一种开方方案
n = x
while True:
if n*n <= x and (n+1)*(n+1) > x:
return n
n = (x/n+n)/2
本来想n=x/2的的,结果1的时候报错了,除数为0
答案
好像没其它方案了
r = x
while r*r > x:
r = (r + x/r) / 2
return r
645. Set Mismatch
题目
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
Note:
The given array size will in the range [2, 10000].
The given array’s numbers won’t have any order.
思路与解答
还要找出来重复的那个啊
d={}
for s in nums:
d[s] = d.get(s,0)+1
l=[0,0]
for n in range(1,len(nums)+1):
if n in d:
if d[n] == 2:
l[0] = n
else:
l[1] = n
return l
答案
一次求出两个数啊,机智
n = len(nums)
expect = n * (n + 1) / 2
actual = sum(nums)
cnt = [0] * (n + 1)
for n in nums:
if cnt[n]:
return [n, expect - actual + n]
cnt[n] += 1
好像利用了一些数学原理。emmmmm
N = len(A)
alpha = sum(A) - N*(N+1)/2
beta = (sum(x*x for x in A) - N*(N+1)*(2*N+1)/6) / alpha
return (alpha + beta) / 2, (beta - alpha) / 2