class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
flag=False
ret=0
pos=1
for s in str:
if s==' ' and not flag:
continue
if s=='+'or s=='-':
if flag:
break
if s=='-':
pos=-1
flag=True
elif s>='0' and s<='9':
ret=ret*10+int(s)
flag=True
else:
break
return pos*min(ret,2**31-1) if pos==1 else pos*min(ret,2**31)
29. Divide Two Integers
用减法来做
减少运算量的技巧:每一次迭代都采用滚筒操作
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
pos=True if (dividend>0 and divisor>0) or (dividend<0 and divisor<0) else False
dividend=abs(dividend)
divisor=abs(divisor)
if divisor==1:
return self.output(dividend,pos)
ret=0
while dividend>=divisor:
multi_divisor=divisor
multi_ret=1
while dividend-multi_divisor>=multi_divisor:
multi_ret=multi_ret+multi_ret
multi_divisor=multi_divisor+multi_divisor
ret+=multi_ret
dividend-=multi_divisor
return self.output(ret,pos)
def output(self,ret,pos):
if pos:
return min(ret,2**31-1)
else:
return -min(ret,2**31)
654. Maximum Binary Tree
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums)==0:
return None
maxnum=max(nums)
root=TreeNode(maxnum)
maxind=nums.index(maxnum)
root.left=self.constructMaximumBinaryTree(nums[:maxind])
root.right=self.constructMaximumBinaryTree(nums[maxind+1:])
return root
找行列的最大值,然后diff就是行列最大值中的最小值与当前位置的差
class Solution:
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
max_x=[]
max_y=[]
for g in grid:
max_x.append(max(g))
for g in zip(*grid):
max_y.append(max(g))
ret=0
for i in range(len(grid)):
for j in range(len(grid[0])):
ret+=min(max_x[i],max_y[j])-grid[i][j]
return ret
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root==None:
return None
#先操作
root.right=self.pruneTree(root.right)
root.left=self.pruneTree(root.left)
#再换
if root.val==0 and root.left==None and root.right==None:
return None
return root
贪心算法,贪心规则第一列全为1(不是就换),其余列尽量多的取1(每一列的1取翻转前后的最大值)。
class Solution(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
for i in range(len(A)):
if A[i][0]==0:
A[i]=[1-j for j in A[i]]
ret=0
for i in range(len(A[0])):
col=[A[j][i] for j in range(len(A))]
ret+= max(sum(col),len(A)-sum(col))*(2**(len(A[0])-i-1))
return ret
深度优先搜索
class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
def dfs( node, path):
if node==len(graph)-1:
res.append( path + [node])
return
for child in graph[node]:
dfs( child, path + [node])
res=[]
dfs(0,[])
return res