相信两年时间可以改变很多事情,所以拼命努力!
1、两数之和
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i, num in enumerate(nums):
if target - num in map:
return([map[target - num], i])
else:
map[num] = i
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
53.最大子序和
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum = 0
res = nums[0]
for num in nums:
if sum >= 0:
sum = sum + num
else:
sum = num
res = max(res, sum)
return res
67.二进制求和
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,2) + int(b, 2)[2:]
使用python中的int函数将string类型强制转换成int型,第二个参数是进制数。
出现的问题
解决方案
要去掉结果前面的二进制数标识,于是结果从第三个字符开始取。
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.简化路径
思路:
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
100、相同的树
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) if p and q else p is q
105、从前序与中序遍历序列构造二叉树
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder or len(preorder)==0:
return None
root = TreeNode(preorder[0])
k = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:k+1], inorder[0:k])
root.right = self.buildTree(preorder[k+1:], inorder[k+1:])
return root
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