1 两数之和
利用哈希表减小时间复杂度
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict={}
for i,num in enumerate(nums):
t2=target-num
if t2 in dict:
return [i,dict[t2]]
dict[num]=i
return []
9 回文数
这里主要是计算倒序数判断是否相等。
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
cur=0
num=x
while num !=0:
cur=cur*10+num%10
num//=10
return cur==x
13 罗马数字转整数
这里是判断如果后面的比前面的大,那么前面的数字就应该减去,加上了的话就减2倍。
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict={'I': 1,'V': 5,'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000}
sum=dict[s[0]]
for char in range(1,len(s)):
if dict[s[char]]>dict[s[char-1]]:
sum=sum-2*dict[s[char-1]]
sum+=dict[s[char]]
return sum
14 最长公共前缀
注意判断strs里的长度如果最大的就是当前的遍历值的情况。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return []
length=len(strs[0])
count=len(strs)
for char in range(length):
c=strs[0][char]
if any(char==len(strs[j]) or c!= strs[j][char] for j in range(1,count)):
return strs[0][:char]
return strs[0]
20 有效的括号
主要使用栈(先进后出)的方法实现,注意pop不能是空栈。
class Solution(object):
def isValid(self, s):
dict={'{':'}','[':']','(':')','?':'?'}
stack=['?']
for i in s:
if i in dict:
stack.append(i)
elif dict[stack.pop()] != i:return False
return len(stack)== 1
21 合并两个有序链表
1、递归法
class Solution(object):
def mergeTwoLists(self, list1, list2):
if not list1:return list2
if not list2:return list1
if list1.val<=list2.val:
list1.next=self.mergeTwoLists(list1.next,list2)
return list1
else:
list2.next=self.mergeTwoLists(list2.next,list1)
return list2
2、迭代法
class Solution(object):
def mergeTwoLists(self, list1, list2):
prehead=ListNode(-1)
pre=prehead
while list1 and list2:
if list1.val<list2.val:
pre.next=list1
list1=list1.next
else:
pre.next=list2
list2=list2.next
pre=pre.next
pre.next=list1 if not list2 else list2
return prehead.next
26 删除有序数组中的重复项
添加复制的小判断,大于等于1才进行复制。
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return []
left=0
needle=1
while needle<len(nums):
if nums[left]!=nums[needle]:
if needle-left>1:
nums[left+1]=nums[needle]
left=left+1
needle+=1
return left+1
27 移除元素
class Solution(object):
def removeElement(self, nums, val):
q=0
count=len(nums)
for p in range(count):
if nums[p] != val:
nums[q]=nums[p]
q+=1
return q
28 字符串中第一个匹配的下标
class Solution(object):
def strStr(self, haystack, needle):
result=haystack.find(needle)
return result
35 搜索插入位置
本题用二分法实现。
class Solution(object):
def searchInsert(self, nums, target):
length=len(nums)
if target>nums[length-1]:
return length
left=0
right=length-1
while left<right:
mid=(left+right)//2
if nums[mid]<target:
left=mid+1
else:
right=mid
return left
58 最后一个单词的长度
class Solution(object):
def lengthOfLastWord(self, s):
char=s.split()
result=len(char[-1])
return result
不用split:(速度好像快一点)
class Solution(object):
def lengthOfLastWord(self, s):
count=0
for char in s[::-1]:
if char ==' ':
if count==0:
continue
else: break
count+=1
return count
66 加一
class Solution(object):
def plusOne(self, digits):
n=len(digits)
carry=1
for i in range(n-1,-1,-1):
digits[i]+=carry
carry=digits[i]//10
digits[i] %= 10
if carry:
digits.insert(0,1)
return digits
67 二进制求和
class Solution(object):
def addBinary(self, a, b):
i=len(a)-1
j=len(b)-1
result=''
carry=0
while i>=0 or j>=0 or carry:
sum=0
if i>=0:
sum+=int(a[i])
if j>=0:
sum+=int(b[j])
sum+=carry
carry=sum//2
char=str(sum%2)
result=char+result
i-=1
j-=1
return result
68 x的平方根
class Solution:
def mySqrt(self,x):
if x<2:
return x
left=1
right=x//2
while left<=right:
mid=(left+right)//2
sqrt=mid*mid
if sqrt<x:
ans=mid
left=mid+1
elif sqrt>x:
right=mid-1
else: return mid
return ans
70 爬楼梯
class Solution(object):
def climbStairs(self, n):
if n==1:
return 1
pre1=1
pre2=1
for i in range(1,n):
r=pre1+pre2
pre1=pre2
pre2=r
return r
83 删除链表中的重复元素
class Solution(object):
def deleteDuplicates(self, head):
if not head:
return head
cur=head
while head.next:
if head.val==head.next.val:
head.next=head.next.next
else:
head=head.next
return cur
88 合并两个有序数组
class Solution(object):
def merge(self, nums1, m, nums2, n):
nums1[m:]=nums2
nums1.sort()
return nums1
94 二叉树的中序遍历
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# res = []
# def dfs(root):
# if not root:
# return
# # 按照 左-打印-右的方式遍历
# dfs(root.left)
# res.append(root.val)
# dfs(root.right)
# dfs(root)
# return res
# 上面是递归
res = []
stack = []
while stack or root:
# 不断往左子树方向走,每走一次就将当前节点保存到栈中
# 这是模拟递归的调用
if root:
stack.append(root)
root = root.left
# 当前节点为空,说明左边走到头了,从栈中弹出节点并保存
# 然后转向右边节点,继续上面整个过程
else:
tmp = stack.pop()
res.append(tmp.val)
root = tmp.right
return res
100 相同的树
class Solution:
def isSameTree(self, p, q):
if not p and not q:
return True
elif not p or not q:
return False
elif p.val != q.val:
return False
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
101 对称二叉树
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root or not (root.left or root.right):
return True
# 用队列保存节点
queue = [root.left,root.right]
while queue:
# 从队列中取出两个节点,再比较这两个节点
left = queue.pop(0)
right = queue.pop(0)
# 如果两个节点都为空就继续循环,两者有一个为空就返回false
if not (left or right):
continue
if not (left and right):
return False
if left.val!=right.val:
return False
# 将左节点的左孩子, 右节点的右孩子放入队列
queue.append(left.left)
queue.append(right.right)
# 将左节点的右孩子,右节点的左孩子放入队列
queue.append(left.right)
queue.append(right.left)
return True
# if not root:
# return True
# def dfs(left,right):
# if not left and not right:
# return True
# elif not left or not right:
# return False
# elif left.val != right.val:
# return False
# return dfs(left.left,right.right) and dfs(left.right,right.left)
# return dfs(root.left,root.right)
# 以上是递归法
104 二叉树的最大深度
class Solution(object):
def maxDepth(self, root):
if not root:
return 0
else:
left_h=self.maxDepth(root.left)
right_h=self.maxDepth(root.right)
return max(left_h,right_h)+1
108 将有序数组转化为搜索二叉树
class Solution(object):
def sortedArrayToBST(self, nums):
def helper(left,right):
if left>right:
return None
mid=(left+right)//2
root=TreeNode(nums[mid])
root.left=helper(left,mid-1)
root.right=helper(mid+1,right)
return root
return helper(0,len(nums)-1)
110 平衡二叉树
class Solution:
def isBalanced(self, root) :
def recur(root):
if not root: return 0
left = recur(root.left)
if left == -1: return -1
right = recur(root.right)
if right == -1: return -1
return max(left, right) + 1 if abs(left - right) <= 1 else -1
return recur(root) != -1
111 二叉树的最小深度
class Solution(object):
def minDepth(self, root):
if not root:
return 0
lh=self.minDepth(root.left)
rh=self.minDepth(root.right)
if not (root.left and root.right):
return lh+rh+1
else:
return min(lh,rh)+1
112 路径总和
class Solution(object):
def hasPathSum(self, root, targetSum):
if not root:
return False
if not root.left and not root.right:
return root.val==targetSum
return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val)
118 杨辉三角
class Solution(object):
def generate(self, numRows):
if numRows==0:
return []
res=[[1]]
while len(res)<numRows:
new=[a+b for a,b in zip(res[-1]+[0],[0]+res[-1])]
res.append(new)
return res
借位相加。
119 杨辉三角二
class Solution(object):
def getRow(self, rowIndex):
row=[1]
for i in range(1,rowIndex+1):
new=row[-1]*(rowIndex-i+1)/i
row.append(new)
return row
121 买卖股票的最佳时机
class Solution(object):
def maxProfit(self, prices):
minprice=int(1e9)
money=0
for i in prices:
money=max(i-minprice,money)
minprice=min(minprice,i)
return mone
125 验证回文串
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# if not s:
# return True
# sgood=''.join(ch.lower() for ch in s if ch.isalnum())
# return sgood==sgood[::-1]
# 在当前字符串上实现
if not s:
return True
right=len(s)-1
left=0
while left<right:
while left<right and not s[left].isalnum():
left+=1
while left<right and not s[right].isalnum():
right-=1
if left<right:
if s[left].lower() != s[right].lower():
return False
left,right=left+1,right-1
return True
136 只出现一次的数字
return reduce(lambda x,y:y^x, nums)
-
reduce()
函数是Python内置的函数,它接受一个函数和一个可迭代对象作为参数,然后将该函数累积地应用到可迭代对象的元素上,从左到右。在这个代码中,reduce()
函数接受了一个lambda
函数和一个名为nums
的可迭代对象作为参数。 -
lambda x, y: y ^ x
:这是一个匿名函数,其中x
和y
是函数的两个参数。函数体是y ^ x
,表示对y
和x
进行异或操作。 -
nums
:这是一个可迭代对象,可能是一个列表、元组或其他可迭代对象。 -
reduce(lambda x, y: y ^ x, nums)
:这行代码的作用是将可迭代对象nums
中的所有元素依次进行异或操作,并返回最终结果。
异或操作(^
)是一种位运算,对于每一对比特位,当相同则结果为0,不同则结果为1。在这种情况下,连续异或操作可以将一系列数字彼此之间进行异或,最终得到一个结果。
141 环形链表
class Solution:
def hasCycle(self, head) :
if not head or not head.next:
return False
slow = fast = head # 乌龟和兔子同时从起点出发
while fast and fast.next:
slow = slow.next # 乌龟走一步
fast = fast.next.next # 兔子走两步
if fast == slow: # 兔子追上乌龟(套圈),说明有环
return True
return False # 访问到了链表末尾,无环
144 二叉树的前序遍历
这里的递归的方法,还可以用迭代法写
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = list()
preorder(root)
return res
145 二叉树的后续遍历
首先是递归,然后是迭代。
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
def dfs(root):
if not root:
return
dfs(root.left)
dfs(root.right)
res.append(root.val)
res=[]
dfs(root)
return res
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return list()
res = list()
stack = list()
prev = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if not root.right or root.right == prev:
res.append(root.val)
prev = root
root = None
else:
stack.append(root)
root = root.right
return res
160 相交链表
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return null
p1=headA
p2=headB
while p1 != p2:
p1=p1.next if p1 else headB
p2=p2.next if p2 else headA
return p1
168 Excel列表名称
这里要注意的是26进制是0-25表示,题目是1-26对应字母。
class Solution(object):
def convertToTitle(self, columnNumber):
"""
:type columnNumber: int
:rtype: str
"""
char=''
while columnNumber>0:
columnNumber-=1
num=columnNumber%26
char=chr(num+ord('A'))+char
columnNumber=columnNumber//26
return char
169 多数元素
1、哈希表:
collections.Counter 是 Python 标准库中 collections 模块提供的一个类,用于对可迭代对象中的元素进行计数。它返回一个字典,其中键是可迭代对象中的元素,值是该元素在可迭代对象中出现的次数。
import collections
counter = collections.Counter(iterable)
iterable是一个可迭代的对象,collections.Counter() 返回的对象是一个 Counter 类的实例
nums = [1, 2, 3, 1, 1, 2, 3, 1, 2, 2]
import collections
counter = collections.Counter(nums)
print(counter)
>>>
Counter({1: 4, 2: 3, 3: 2})
max() 函数是 Python 内置函数之一,用于返回可迭代对象中的最大值。它的语法如下:
max(iterable, *[, key, default])
'''
iterable 是一个可迭代对象,如列表、元组、集合等。
key 是一个函数,用于指定一个可调用对象,用于从每个元素中提取用于比较的键。默认为 None,表示直接比较元素本身的大小。
default 是一个可选参数,用于指定当可迭代对象为空时返回的默认值。如果不提供 default 参数并且可迭代对象为空,那么会引发 ValueError 异常。
'''
# 示例 1:找出列表中的最大值
numbers = [1, 5, 3, 9, 7]
max_number = max(numbers)
print(max_number) # 输出:9
# 示例 2:找出字符串中 ASCII 值最大的字符
text = "Hello"
max_char = max(text)
print(max_char) # 输出:o
# 示例 3:使用 key 函数自定义比较规则
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 70},
{"name": "Charlie", "score": 95}
]
top_student = max(students, key=lambda x: x["score"])
print(top_student) # 输出:{'name': 'Charlie', 'score': 95}
解题:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
'''
key=counts.get 和 key=lambda x: counts.get(x) 都会产生相同的结果,
都会将每个元素作为参数传递给 counts.get() 函数.
'''
时间复杂度:O(n);空间复杂度:O(n)
2、排序法
最中间的元素一定是众数。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums) // 2]
'''
时间复杂度:O(nlogn)。
空间复杂度:O(logn)。
'''
3、摩尔投票法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
171 Excel表列序号
是168思想反着来的。
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
number, multiple = 0, 1
for i in range(len(columnTitle) - 1, -1, -1):
k = ord(columnTitle[i]) - ord("A") + 1
number += k * multiple
multiple *= 26
return number
191 位1的个数
1、循环
'''生成器表达式的基本语法是 (expression for item in iterable if condition)'''
# 将列表中的每个元素加倍
doubled = (x * 2 for x in [1, 2, 3, 4, 5])
print(list(doubled)) # 输出: [2, 4, 6, 8, 10]
# 仅保留偶数
even_numbers = (x for x in range(10) if x % 2 == 0)
print(list(even_numbers)) # 输出: [0, 2, 4, 6, 8]
在Python中,<< 是位运算符,表示左移操作符。它用于将一个数的二进制表示向左移动指定的位数。
例如,对于 x = 5(二进制表示为 101),执行 x << 2 将得到 10100,即十进制的 20。
这是因为 101 左移两位后变成了 10100,低位补0。
1<<i 是一个位运算操作,它将十进制数 1 左移 i 位。这意味着我们生成了一个只有第 i 位是 1,其余位都是 0 的二进制数。例如,当 i 为 0 时,结果是 1;当 i 为 1 时,结果是 2;当 i 为 2 时,结果是 4,依此类推。
解题:
class Solution:
def hammingWeight(self, n: int) -> int:
ret = sum(1 for i in range(32) if n & (1 << i))
return ret
'''
时间复杂度:O(k),其中 k 是 int 型的二进制位数,k=32。
我们需要检查 n 的二进制位的每一位,一共需要检查 32 位。
空间复杂度:O(1),我们只需要常数的空间保存若干变量。
'''
2、python内置函数
bin(n).count('1')
# bin() 函数用于将整数转换为二进制字符串表示形式
s = "hello world"
count_e = s.count('e')
print(count_e) # 输出: 1
3、位运算优化
class Solution:
def hammingWeight(self, n: int) -> int:
ret = 0
while n:
n &= n - 1
ret += 1
return ret
'''
时间复杂度:O(logn)。循环次数等于 n 的二进制位中 1 的个数,最坏情况下 n 的二进制位全部为 1。我们需要循环 logn 次。
空间复杂度:O(1),我们只需要常数的空间保存若干变量。
'''
202 快乐数
快慢指针的思想,尤其注意while循环条件
def isHappy(self, n: int) -> bool:
def get_next(number):
total_sum = 0
while number > 0:
number, digit = divmod(number, 10)
total_sum += digit ** 2
return total_sum
slow_runner = n
fast_runner = get_next(n)
while fast_runner != 1 and slow_runner != fast_runner:
slow_runner = get_next(slow_runner)
fast_runner = get_next(get_next(fast_runner))
return fast_runner == 1
时间复杂度:O(logn)
空间复杂度:O(1)
203 消除链表元素
1、递归法
理解:head.next指向的应该是head.next后移除了val的链表(递归操作)。递归的终止条件head是否为空,如果为空,就返回head([ ])。return的是链表的第一个元素,也就是如果=val就返回head.next。
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return head
head.next=self.removeElements(head.next,val)
return head.next if head.val==val else head
时间复杂度:O(n),其中 n 是链表的长度。递归过程中需要遍历链表一次。
空间复杂度:O(n),其中 n 是链表的长度。空间复杂度主要取决于递归调用栈,最多不会超过 n 层。
2、迭代法
需要初始化一个dummyhead dummyhead.next=head。
注意while循环的条件和return的值。
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return head
dummy_head = ListNode(0) # 创建一个值为0的dummy节点
dummy_head.next = head
temp=dummy_head
while temp.next:
if temp.next.val==val:
temp.next=temp.next.next
else:temp=temp.next
return dummy_head.next
205 同构字符串
有个题解:index()会返回该元素在str内首次出现的index,将"egg"通过该方式转换为[0,1,1],同理如果其他str也是ABB格式,那么转完也应该是[0,1,1]
return True if [s.index(i) for i in s] == [t.index(j) for j in t] else False
哈希表:
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t): # 如果两个字符串长度不同,则它们一定不是同构的
return False
char_map_s = {} # 用于存储 s 中字符到 t 中字符的映射关系
char_map_t = {} # 用于存储 t 中字符到 s 中字符的映射关系
for char_s, char_t in zip(s, t): # 遍历 s 和 t 中的字符
if char_s in char_map_s: # 如果当前字符已经在 s 中存在映射
if char_map_s[char_s] != char_t: # 检查映射关系是否一致
return False
else:
char_map_s[char_s] = char_t # 建立 s 到 t 的映射关系
if char_t in char_map_t: # 如果当前字符已经在 t 中存在映射
if char_map_t[char_t] != char_s: # 检查映射关系是否一致
return False
else:
char_map_t[char_t] = char_s # 建立 t 到 s 的映射关系
return True # 遍历完成后没有发现不一致的映射关系,说明两个字符串是同构的
206 反转链表
1、迭代法
我前面是谁,我是谁,我后面是谁。
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
pre=None
cur=head
while cur:
next=cur.next
cur.next=pre
pre=cur
cur=next
return pre
时间复杂度:O(n);空间复杂度:O(1)
2、递归法
head.next.next=head
需要注意的是 head的下一个节点必须指向 ∅。如果忽略了这一点,链表中可能会产生环。
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
newhead=self.reverseList(head.next)
head.next.next=head
head.next=None
return newhead
以1234为例:
1、newhead=re(2);2、调用re(2) newhead=re(3);3、调用re(3) newhead=re(4);4、调用re(4)这时head.next=None,返回4;4、跟步骤3对应,newhead=4,继续执行,3.next.next=3,得到4-3;5、跟步骤2 对应 执行re(3)后面部分 得到4-3-2--------省略。
217 存在重复元素
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
list=[]
for num in nums:
if num not in list:
list.append(num)
else:
return True
return False
》》》
超时了!!!!
1、set
用set()集合没有显示超时: set 是一种无序、不重复的数据集合。它类似于数学中的集合,可以存储各种类型的元素,并且确保其中的每个元素都是唯一的。
无序性;唯一性,可变性。
my_set = {1, 2, 3, 4, 5} #{}
my_set = set([1, 2, 3, 4, 5]) #set()
检查列表中是否包含某个元素的操作的时间复杂度是 O(n),而且还需要进行插入操作,其时间复杂度也是 O(n)。集合使用哈希表实现,所以检查元素是否存在的操作的时间复杂度是 O(1),这使得集合非常适合于查找、删除重复元素等操作。
(列表添加元素没有add,使用的是append和insert)
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
seen = set() # 使用集合存储已经遍历过的数字
for num in nums:
if num in seen:
return True
seen.add(num)
return False
2、字典
在 Python 中,可以使用字典来实现类似的功能。字典的键就相当于集合中的元素,而字典的值可以是任意类型,但在这里我们可以将值设置为True\None 等占位符。
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
hash_table = {}
for x in nums:
if x in hash_table:
return True
hash_table[x] = True
return False
219 存在重复元素2.0
1、哈希表:字典
在 Python 中, enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环中。
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dict={}
for i,num in enumerate(nums):
if num in dict and i-dict[num]<=k:
return True
dict[num]=i
return False
2、集合加滑动窗口
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
jihe=set()
for i,num in enumerate(nums):
if i>k:
jihe.remove(nums[i-k-1])
if num in jihe:
return True
else:
jihe.add(num)
return False
222 完全二叉树的节点个数
很容易的递归但是没有利用完全二叉树的特点:
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return self.countNodes(root.left)+self.countNodes(root.right)+1
完全二叉树的定义:它是一棵空树或者它的叶子节点只出在最后两层,若最后一层不满则叶子节点只在最左侧。
class Solution(object):
def countNodes(self, root):
#二叉树的层数
def countlevel(root):
if not root:
return 0
return max(countlevel(root.left),countlevel(root.right))+1
if not root:
return 0
left=countlevel(root.left)
right=countlevel(root.right)
if left==right:
return (1<<left)+self.countNodes(root.right)
else:
return (1<<right)+self.countNodes(root.left)
1<<left 是在计算pow(2,left) <<按位左移
225 用队列实现栈
双端队列(deque,全称为 double-ended queue)。
import collections
# 创建一个空的双端队列
my_deque = collections.deque()
my_deque.append(x)
# append(x):在双端队列的右侧添加元素 x。
my_deque.appendleft(x)
# appendleft(x):在双端队列的左侧添加元素 x。
x = my_deque.pop()
# pop():移除并返回双端队列右侧的元素。
x = my_deque.popleft()
# popleft():移除并返回双端队列左侧的元素。
my_deque.extend(iterable)
# extend(iterable):在双端队列右侧扩展,追加一个可迭代对象中的所有元素。
my_deque.extendleft(iterable)
# extendleft(iterable):在双端队列左侧扩展,追加一个可迭代对象中的所有元素。
my_deque.clear()
# clear():清空双端队列中的所有元素。
class MyStack(object):
def __init__(self):
self.queue=collections.deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.queue.append(x)
def pop(self):
"""
:rtype: int
"""
return self.queue.pop()
def top(self):
"""
:rtype: int
"""
return self.queue[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.queue