51、不用加减乘除做加法
直接用sum函数。看别人的题解用二进制的异或和与运算符。
# -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
return sum([num1, num2])
52、二叉搜索树与双向链表
想了一会没想出来,虽然知道使用中序遍历加递归,但是用代码实现不了。于是参考别人的代码:
class Solution:
def __init__(self):
self.head = None
self.tail = None
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
self.Convert(pRootOfTree.left)
if self.head == None:
self.head, self.tail = pRootOfTree, pRootOfTree
else:
self.tail.right = pRootOfTree
pRootOfTree.left = self.tail
self.tail = pRootOfTree
self.Convert(pRootOfTree.right)
return self.head
53、复杂链表的复制
没有想到好的办法,参考了别人的思路:https://blog.csdn.net/qq_33431368/article/details/79296360
可以说是很巧妙了。不过好像直接用字典写起来比较快。
# -*- coding:utf-8 -*-
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return None
cur = pHead
while cur:
node = RandomListNode(cur.label)
node.next = cur.next
cur.next = node
cur = node.next
cur = pHead
while cur:
node = cur.next
if cur.random:
node.random = cur.random.next
cur = cur.next.next
old = pHead
pHead = pHead.next
while old.next:
node = old.next
old.next = node.next
old = node
return pHead
53、字符串的排列
可以用递归写
class Solution:
def Permutation(self, ss):
# write code here
def getall(ss):
if not ss:
return None
if len(ss) == 1:
return [ss]
rst = []
for i in range(len(ss)):
rest = getall(ss[:i] + ss[i + 1:])
for j in rest:
rst.append(ss[i] + j)
return rst
temp = getall(ss)
return sorted(list(set(temp)))
自己测试的没问题,但是牛客网上过不了。不知道是不是因为python版本的问题,牛客网也不会像leetcode一样说哪个测试用例过不了。
55、二进制中1的个数
补码不知道是啥= =。计算机基础知识不扎实,先放着吧
网友评论