def bubble_sort(arr1):
for i in range(len(arr1)):
for j in range(len(arr1[1:])):
if arr1[i] < arr1[j]:
arr1[i], arr1[j] = arr1[j], arr1[i]
return arr1
# -*- coding:utf-8 -*-
class Solution:
def more_than_half(self, numbers):
# write code here
dict = {}
for num in numbers:
if num not in dict:
dict[num] = 1
else:
dict[num]+=1
if dict[num] > len(numbers)/2:
return num
return 0
class Solution(object):
def lengthOfLongestSubstring(self, s):
res = 0;i = 0; val = ""
for j in range(len(s)):
if s[j] not in s[i:j]:
res = max(res,j+1-i)
else:
i += s[i:j].index(s[j]) + 1
return res
def fib();
a, b = 0, 1
while true:
yield a
a, b = b, a+b
from itertools import islice
print list(islice(fib(), 5))
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 申请两个节点,pre和 cur,pre指向None
pre = None
cur = head
# 遍历链表,while循环里面的内容其实可以写成一行
# 这里只做演示,就不搞那么骚气的写法了
while cur:
# 记录当前节点的下一个节点
tmp = cur.next
# 然后将当前节点指向pre
cur.next = pre
# pre和cur节点都前进一位
pre = cur
cur = tmp
return pre
class Solution(object):
def twoSum(self, nums, target):
_dict = {}
for i, m in enumerate(nums):
if _dict.get(target - m) is not None:
return [_dict.get(target - m), i]
_dict[m] = i
def binary_chop(alist, data):
"""
非递归解决二分查找
"""
n = len(alist)
first = 0
last = n - 1
while first <= last:
mid = (last+first)//2
if alist[mid] > data:
last = mid - 1
elif alist[mid] < data:
first = mid + 1
else:
return True
return False
def binary_chop2(alist, data):
"""
递归解决二分查找
"""
n = len(alist)
if n < 1:
return False
mid = n // 2
if alist[mid] > data:
return binary_chop2(alist[0:mid], data)
elif alist[mid] < data:
return binary_chop2(alist[mid+1:], data)
else:
return True
if __name__ == "__main__":
lis = [2,4, 5, 12, 14, 23]
if binary_chop(lis, 12):
print('ok')
else:
print('false')
defmerge_sort(arr1):iflen(arr1)<2:return arr1 half =int(len(arr1) /2) left_arr1 =merge_sort(arr1[:half]) right_arr1 =merge_sort(arr1[half:])returnmerge(left_arr1, right_arr1)defmerge(left,right): result = []while left and right: result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) result.extend(left) result.extend(right)return result
defquick_sort(arr1):iflen(arr1)<2:return arr1else: pivot = arr1[0] less = [i for i in arr1[1:]if i < pivot] greater = [j for j in arr1[1:]if j >= pivot]returnquick_sort(less)+ [pivot] +quick_sort(greater)