7、反转整数
反转字符串 str[::-1]
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = int(str(x)[::-1]) if x>=0 else - int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0
21、合并两个有序列表
在Python中创建一个链表的方式是:head = ListNode(0)
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0)
s = l3
while l1 and l2 :
if l1.val >= l2.val:
s.next = l2
l2 = l2.next
s = s.next
else :
s.next = l1
l1 = l1.next
s = s.next
if l1 :
s.next = l1
if l2 :
s.next = l2
return l3.next
69.x的平方根
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 0, x
while left<=right:
mid = (left+right)//2
if mid**2 > x:
right = mid -1
else:
left = mid + 1
return left -1
71.简化路径
思路:
1. 将字符串按“/”划分,存入数组。
2.将有意义的字符串入栈,如果遇到“..”则出栈。
3. 最后将栈中剩余字符串以”/”连接,并返回。未空默认返回“/”
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path_array = path.split("/")
stack = []
res_path = ""
for item in path_array :
if item not in ["", ".", ".."]:
stack.append(item)
if ".." == item and stack:
stack.pop(-1)
if [] == stack:
return "/"
for item in stack:
res_path += "/" + item +""
return res_path
94.二叉树的遍历
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
if root == None:
return []
res += self.inorderTraversal(root.left)
res.append(root.val)
res += self.inorderTraversal(root.right)
return res
717、1比特、2比特字符
class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
p = 0
for i in reversed(range(len(bits)-1)):
if bits[i] == 0:
break
p ^= bits[i]
return p == 0