if __name__ == "__main__": data = [1,2,3,4,3,5,2,8,1,4] print(quick_sort(data))
双指针写法
归并排序
堆排序
计数排序
查找算法
二分查找
非递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defbinary_search(data,value): left = 0 right = len(data)-1
while left<=right: mid = (left+right)//2 if value == data[mid]: return mid if value right = mid -1 if value>data[mid]: left = mid +1 returnNone
if __name__ == "__main__": print(binary_search([1,2,3,4,5,6],5))
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defbinary_search(data,left, right, value): if left>right: return-1 mid = (left+right)//2 if value == data[mid]: return mid if value right = mid -1 if value>data[mid]: left = mid +1 return binary_search(data, left, right, value)
if __name__ == "__main__": print(binary_search([1,2,3,4,5,6],0,5,5))
defFind(target, array): rows = len(array) cols = len(array[0]) i,j = 0,cols-1 while iand j>=0: if array[i][j] == target: returnTrue if array[i][j] > target: j -= 1 else: i += 1 returnFalse
python 不支持 i++ 这种写法,改用 i+=1
替换空格
请实现一个函数,将一个字符串中的每个空格替换成 “%20”。例如,当字符串为 We Are Happy. 则经过替换之后的字符串为 We%20Are%20Happy。
思路:空格一个字符,替换后变成3个字符,因此字符串变长了,应该从后向前替换。
1 2 3 4 5 6 7 8 9
classSolution: defreplace_space(self, s): result = '' for i in range(len(s)-1, -1, -1): if s[i] == ' ': result = '%20' + result else: result = s[i] + result return result