爬楼梯
def clambStairs(n):
x,y = 1,1
for _ in range(1,n):
x,y = y,x+y
return y
clambStairs(10)
89
clambStairs(2)
2
编辑距离
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
print(dp)
for i in range(m + 1):
print('i =', i)
dp[i][0] = i
for j in range(n + 1):
print('j = ', j)
dp[0][j] = j
print(dp)
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = min(
dp[i - 1][j - 1] +
(0 if word1[i - 1] == word2[j - 1] else 1),
dp[i - 1][j] + 1, dp[i][j - 1] + 1)
print('i = {0},j = {1},dp[i][j] = {2}'.format(i, j, dp[i][j]))
return dp[i][j]
solu = Solution()
solu.minDistance('zhou','lu')
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
i = 0
i = 1
i = 2
i = 3
i = 4
j = 0
j = 1
j = 2
[[0, 1, 2], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]]
i = 1,j = 1,dp[i][j] = 1
i = 1,j = 2,dp[i][j] = 2
i = 2,j = 1,dp[i][j] = 2
i = 2,j = 2,dp[i][j] = 2
i = 3,j = 1,dp[i][j] = 3
i = 3,j = 2,dp[i][j] = 3
i = 4,j = 1,dp[i][j] = 4
i = 4,j = 2,dp[i][j] = 3
3
小顶堆 topk
import heapq
def heapsort(data, hp_size=3):
h = []
for i in range(len(data)):
if i >= hp_size:
heapq.heappushpop(h, data[i])
else:
heapq.heappush(h, data[i])
return [heapq.heappop(h) for _ in range(len(h))]
res = heapsort([6,2,1,-4,9,4,0])
print(res)
[4, 6, 9]
h=[1,2,4,5,6,32,45]
heapq.heappushpop(h,-1)
-1
快排序
# 方式一
def quick_sort(array, left, right):
if left >= right:
return
low = left
high = right
key = array[low]
while left < right:
while left < right and array[right] > key:
right -= 1
array[left] = array[right]
while left < right and array[left] <= key:
left += 1
array[right] = array[left]
array[right] = key
quick_sort(array, low, left - 1)
quick_sort(array, left + 1, high)
print(quick_sort(arr,0,len(arr)-1))
print(arr)
None
[2, 2, 3, 5, 6, 7, 10, 23, 43, 78, 254, 875]
quick_sort(arr,0,len(arr)-1)
# 方式二 常用(ZL)
def quick_sort(arr,start=0,end=None):
if end is None:
end = len(arr)-1
if end<=start:
return(arr)
i,j = start,end
ref = arr[start]
while j>i:
if arr[j]>= ref:
j = j - 1
else:
# 此处使用一行语句交换3个元素的值
# arr[i],arr[j],arr[i+1] = arr[j],arr[i+1],arr[i]
arr[i],arr[j],arr[i+1] = arr[j],arr[i+1],arr[i]
# arr[i],arr[j]=arr[j],arr[i]
i = i + 1
quick_sort(arr,start=start,end = i-1)
quick_sort(arr,start=i+1,end = end)
return(arr)
print(quick_sort([45,91,1,3,3,2,2,6,6,6,5,5,7]))
[1, 2, 2, 3, 3, 5, 5, 6, 6, 6, 7, 45, 91]
# 方式三
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: willard
'''
def sub_sort(array,low,high):
key = array[low]
while low < high:
while low < high and array[high] >= key:
high -= 1
while low < high and array[high] < key:
array[low] = array[high]
low += 1
array[high] = array[low]
array[low] = key
return low
def quick_sort1(array,low,high):
if low < high:
key_index = sub_sort(array,low,high)
quick_sort1(array,low,key_index)
quick_sort1(array,key_index+1,high)
#array = [8,10,9,6,4,16,5,13,26,18,2,45,34,23,1,7,3]
array1 = [7,3,5,6,2,4,1]
print (array1)
quick_sort1(array1,0,len(array1)-1)
print (array1)
[7, 3, 5, 6, 2, 4, 1]
[1, 2, 3, 4, 5, 6, 7]
# 方式四 不能有重复元素
def quick_sort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less_than_pivot = [x for x in array if x< pivot]
more_than_pivot = [x for x in array if x> pivot]
return quick_sort(less_than_pivot) + [pivot] + quick_sort(more_than_pivot)
arr = [10,2,43,5,6,7,875,23,254,78,3,2]
arr1 = [1,2]
quick_sort(arr)
[2, 3, 5, 6, 7, 10, 23, 43, 78, 254, 875]
二分查找
# 实现一
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : xiaoke
def binary_search(alist, item):
"""二分查找 非递归方式"""
n = len(alist)
start = 0
end = n - 1
while start <= end:
mid = (start + end) // 2
if alist[mid] == item:
return True
elif item < alist[mid]:
end = mid - 1
else:
start = mid + 1
return False
# 实现二
def binary_search_2(alist, item):
"""二分查找 递归方式"""
n = len(alist)
if 0 == n:
return False
mid = n // 2
if alist[mid] == item:
return True
elif item < alist[mid]:
return binary_search_2(alist[:mid], item)
else:
return binary_search_2(alist[mid + 1:], item)
if __name__ == '__main__':
li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
# print(binary_search(li, 55))
# print(binary_search(li, 100))
print(binary_search_2(li, 55))
print(binary_search_2(li, 100))
# 实现三
def binary_search(arr,target):
start,end = 0,len(arr)-1
while True:
if end - start <=1:
if target == arr[start]:
return(start)
elif target == arr[end]:
return(end)
else:
return(-1)
mid = (start + end)//2
if arr[mid]>=target:
end = mid
else:
start = mid
print(binary_search([1,4,7,8,9,12],9))
print(binary_search([1,4,7,8,9,12],3))
斐波那契数列
def fib(n):
if n <= 0:
return "请输入正整数"
if n == 1:
return [0]
x,y = 1,1
a = [0]
for _ in range(1,n):
x,y = y,x+y
a.append(x)
return a
fib(0)
'请输入正整数'
fib(1)
[0]
fib(2)
[0, 1]
fib(3)
[0, 1, 2]
fib(4)
[0, 1, 2, 3]
fib(5)
[0, 1, 2, 3, 5]
fib(6)
[0, 1, 2, 3, 5, 8]
fib(10)
[0, 1, 2, 3, 5, 8, 13, 21, 34, 55]
两数之和
def sum_of_two(arr,target):
dic = {}
for i,x in enumerate(arr):
j = dic.get(target-x,-1)
if j != -1:
return((j,i))
else:
dic[x] = i
return([])
arr = [2,7,4,9]
target = 6
print(sum_of_two(arr,target))
(0, 2)
最大回溯
题目形式:有一个数组,求其中两个数x,y,满足x的索引小于y的索引,使得 x-y 最大。例如 arr = [3,7,2,6,4,1,9,8,5], 最大回撤是6,对应的x=7,y=1。
def max_drawdown(arr):
assert len(arr)>2, "len(arr) should > 2!"
x,y = arr[0:2]
xmax = x
maxdiff = x-y
for i in range(2,len(arr)):
if arr[i-1] > xmax:
xmax = arr[i-1]
if xmax - arr[i] > maxdiff:
maxdiff = xmax - arr[i]
x,y = xmax,arr[i]
print("x=",x,",y=",y)
return(maxdiff)
print(max_drawdown([3,7,2,6,4,1,9,8,5]))
x= 7 ,y= 1
6
合并连个有序数组
def merge_sorted_array(a,b):
c = []
i,j = 0,0
while True:
if i==len(a):
c.extend(b[j:])
return(c)
elif j==len(b):
c.extend(a[i:])
return(c)
else:
if a[i]<b[j]:
c.append(a[i])
i=i+1
else:
c.append(b[j])
j=j+1
print(merge_sorted_array([1,2,6,8],[2,4,7,10]))
[1, 2, 2, 4, 6, 7, 8, 10]
最大连续子数组之和
def max_sub_array(arr):
n = len(arr)
maxi,maxall = arr[0],arr[0]
for i in range(1,n):
maxi = max(arr[i],maxi + arr[i])
maxall = max(maxall,maxi)
return(maxall)
print(max_sub_array([1,5,-10,2,5,-3,2,6,-3,1]))
12
最长不重复子串
def longest_substr(s):
dic = {}
start,maxlen,substr = 0,0,""
for i,x in enumerate(s):
if x in dic:
start = max(dic[x]+1,start)
dic[x] = i
else:
dic[x] = i
if i-start+1>maxlen:
maxlen = i-start+1
substr = s[start:i+1]
return(substr)
print(longest_substr("abcbefgf"))
print(longest_substr("abcdef"))
print(longest_substr("abbcddefh"))
cbefg
abcdef
defh
全排列
import numpy as np
def permutations(arr):
if len(arr)<=1:
return([arr])
t = [arr[0:1]]
i = 1
while i<=len(arr)-1:
a = arr[i]
t = [xs[0:j]+[a]+xs[j:] for xs in t for j in range(i+1)]
t = np.unique(t,axis=0).tolist()
i = i+1
return(t)
print(permutations([1,1,3]))
[[1, 1, 3], [1, 3, 1], [3, 1, 1]]
三数之和
def sum_of_three(arr,target):
assert len(arr)>=3,"len(arr) should >=3!"
arr.sort()
ans = set()
for k,c in enumerate(arr):
i,j = k+1,len(arr)-1
while i<j:
if arr[i]+arr[j]+c <target:
i = i+1
elif arr[i]+arr[j]+c > target:
j = j-1
else:
ans.update({(arr[k],arr[i],arr[j])})
i = i+1
j = j-1
return(list(ans))
print(sum_of_three([-3,-1,-2,1,2,3],0))
[(-2, -1, 3), (-3, 1, 2)]
网友评论