1,两数之和
以值为键值,下标为值创建字典
加快速度
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={};
for i,num in enumerate(nums):
if hashmap.get(target-num) is not None:
return [hashmap.get(target-num),i]
hashmap[num]=i
17. 电话号码的字母组合 DFS 相同步长的所有路径个数
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
phone={'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n','o'],
'7':['p','q','r','s'],
'8':['t','u','v'],
'9':['w','x','y','z']}
res=[]
def dfs(s,index):
if index==len(digits):
res.append(s)
return
for s1 in phone[digits[index]]:
dfs(s+s1,index+1)
if digits:#特殊情况:digits为空时res为[''],而不是[]
dfs('',0)
return res
64. 最小路径和 动态规划 无初始化型
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n=len(grid)
m=len(grid[0])
dp=[[float('inf')]*m for i in range(2)]
for i in range(n):
for j in range(m):
if i==0 and j==0:
dp[i%2][j]=grid[i][j]
elif i==0:
dp[i%2][j]=dp[i%2][j-1]+grid[i][j]
elif j==0:
dp[i%2][j]=dp[(i-1)%2][j]+grid[i][j]
else:
dp[i%2][j]=min(dp[(i-1)%2][j]+grid[i][j],dp[i%2][j-1]+grid[i][j])
return dp[(n-1)%2][m-1]
69. x 的平方根 二分查找
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
up=x
down=0
mid=0
if x<=1:
return x
while(up>down):
mid=(up+down)//2
sqrt=mid**2
sqrt1=(mid+1)**2
if sqrt>x:
up=mid
elif sqrt<x:
if sqrt1>x:
break
down=mid
else:
break
return mid
75. 颜色分类(三指针)
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
righ=len(nums)-1
left=0
new=0
while new<=righ:
if nums[new]==0:
nums[new],nums[left]=nums[left],nums[new]
left+=1
new+=1
elif nums[new]==1:
new+=1
else:
nums[new],nums[righ]=nums[righ],nums[new]
righ-=1
return nums
迭代法
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
a=nums.count(0)
b=nums.count(1)
c=nums.count(2)
nums[:a]=[0]*a
nums[a:a+b]=[1]*b
nums[a+b:a+b+c]=[2]*c
return nums
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p=headA
q=headB
stack={}
while p:
stack[p]=1
p=p.next
while q:
if q in stack:
return q
q=q.next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p=headA #设置q为headA的链表头
q=headB
while q!=p:
p=p.next if p else headA #如果p是none即最后值,则执行p=headA即跳到链头
q=q.next if q else headB